0

I was wondering how I can solve the following conversion problem of a raster file: when I try to convert the values from the raster (r) from numeric into a factor via as.factor(r) always the error appears: "Error in 1:ncol(r) : argument of length 0".

r <- raster(ncol=5, nrow=5)
values(r) <- 1:ncell(r)
as.factor(r)

I have to figure out how to convert a numeric raster into a factor raster for a predict() calculation within the raster package.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112

1 Answers1

1

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
Mr.ecos
  • 447
  • 1
  • 6
  • 13