【问题标题】:conversion error from numeric to factor in raster: Error in 1:ncol(r) : argument of length 0, r command: as.factor()光栅中从数值到因子的转换错误:1:ncol(r) 中的错误:长度为 0 的参数,r 命令:as.factor()
【发布时间】:2014-06-23 09:48:37
【问题描述】:
我想知道如何解决光栅文件的以下转换问题:当我尝试通过 as.factor(r) 将光栅 (r) 中的值从数字转换为因子时,总是会出现错误:" 1:ncol(r) 中的错误:长度为 0" 的参数。
r <- raster(ncol=5, nrow=5)
values(r) <- 1:ncell(r)
as.factor(r)
我必须弄清楚如何将数值栅格转换为因子栅格,以便在栅格包中进行 predict() 计算。
【问题讨论】:
标签:
r
type-conversion
raster
file-conversion
r-factor
【解决方案1】:
迟到总比不回答好?也许它会对其他人有所帮助。
错误例如Error in 1:ncol(r) : argument of length 0 似乎是真实的,并且至少有一个论坛帖子说这是因为包作者使用ncol() 而不是seq_along();但我认为它可以解决。如果您查看raster::as.factor() 文档中的示例,您将看到上面代码示例之后的后续步骤;
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