Better late than never answer? Maybe it will be helpful to someone else.
The error e.g Error in 1:ncol(r) : argument of length 0
appears to be real and at least one forum post said it was because of the package author using ncol()
instead of seq_along()
; but I think it can be gotten around. If you look at the example in the documentation for raster::as.factor()
you will see the next steps after your code example above;
r <- raster(nrow=10, ncol=10) # make a raster
r[] <- runif(ncell(r)) * 10 # assign it values
is.factor(r) # see that it is not a factor
r <- round(r) # round to make values to be facotrs
f <- as.factor(r) # this is the point you ended above
is.factor(f) # this will show that it is a factor
x <- levels(f)[[1]] # these steps create the factor levels
x
x$code <- letters[10:20] # use your own factor codes here
levels(f) <- x # assigns the levels to the raster
levels(f)
f # you will see the error replaced with factor levels