I created a script where I have a working directory with several png images with a greyscale map in it. I want to convert the greyscale color chart to a viridis color chart to show to occurrences of species on it.
However when I run my code, the black pixels are also converted (=no data because of the sea) to a color so that the continent is not visible anymore. Therefore I inserted an command where pixels with a grayscale value less than 5 have to be white in the output file but now I got this error:
Error in img[img[, , 1] < 5, 1:3] <- c(255, 255, 255) :
incorrect number of subscripts on matrix
Conversion of greyscale to viridis whereby the sea has a value as well instead of white:

Script:
library(png)
library(viridisLite)
# Get list of PNG files in working directory
png_files <- list.files(pattern = "\\.png$")
# Loop through PNG files and convert to viridis color chart PNG
for (i in 1:length(png_files)) {
in_file <- png_files[i]
out_file <- gsub("\\.png$", "_viridis.png", in_file)
# Read the PNG file
img <- readPNG(in_file)
# Convert pixels with grayscale value less than 5 to white
img[img[, , 1] < 5, 1:3] <- c(255, 255, 255)
# Convert grayscale values to viridis colors
intmat <- 255 * img[, , 1]
virmat <- viridis(256)[intmat + 1]
virmat <- c(substr(virmat, 2, 3), substr(virmat, 4, 5),
substr(virmat, 6, 7), substr(virmat, 8, 9))
virmat <- as.numeric(as.hexmode(virmat))/255
dim(virmat) <- c(dim(intmat), 4)
# Write the viridis PNG file
writePNG(virmat, out_file)
}