R将函数应用于内存中

时间:2017-01-10 22:41:42

标签: r list lapply

我的记忆中有光栅。例如:

library(raster)

> nclc1B
class       : RasterLayer 
dimensions  : 212, 406, 86072  (nrow, ncol, ncell)
resolution  : 2, 2  (x, y)
extent      : 662643.7, 663455.7, 3993067, 3993491  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=12 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs 
data source : in memory
names       : band1 
values      : 3.051758e-05, 21.49905  (min, max)

栅格是“nclc1B” - “nclc21B”。它们是相邻的,但没有相同的范围。要获取所有名称以便我可以处理它们,我使用了

filna <- ls(pattern="nclc*.")
filnb <- gsub("nclc","",filna)
filnc <- as.numeric(gsub("B","",filnb))
filna <- filna[order(filnc)]

> str(filna)
chr [1:21] "nclc1B" "nclc2B" "nclc3B" "nclc4B" "nclc5B" "nclc6B" "nclc7B" "nclc8B" ...

> dput(filna)
c("nclc1B", "nclc2B", "nclc3B", "nclc4B", "nclc5B", "nclc6B", 
"nclc7B", "nclc8B", "nclc9B", "nclc10B", "nclc11B", "nclc12B", 
"nclc13B", "nclc14B", "nclc15B", "nclc16B", "nclc17B", "nclc18B", 
"nclc19B", "nclc20B", "nclc21B")

我认为,通过名称列表,我可以使用ncell来查找每个相应栅格的单元格数量,以及我为一些简单处理编写的小函数。

> lapply(filna, ncell)
[[1]]
[1] 1

[[2]]
[1] 1

[[3]]
[1] 1
... (the other 18 were all "1" as well)


do.call(ncell, filna)
> do.call(ncell, list(filna))
[1] 21

我期待列表中每个栅格的结果为10,000s。

> ncell(nclc1B)
[1] 86072

所以,我期待一个列表或矢量,如“86072,84000,89000,......”

我的问题似乎是当我创建名称列表时,名称将保存为与内存中的栅格无关的字符串,并且函数正在寻找其他对象。这看起来像是非常基本的东西,但我没有编程的背景,只知道R中的基本知识,所以我可能会忽略一些明显的东西。这个question看起来与我的相似,但我不是在尝试写文件。我试过了

> raster(filna[1])
Error in .local(.Object, ...) : 
`c:\Documents\output\nclc1B' does not exist in the file system, and is not recognised as a supported dataset name.


Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer",  : 
Cannot create a RasterLayer object from this file. (file does not exist)
> rasterize(filna[1])
Error in (function (classes, fdef, mtable)  : 
unable to find an inherited method for function ‘rasterize’ for signature ‘"character", "missing"’

我以前遇到过这个问题。通常,我使用listoffiles <- ls(),取listoffiles并尝试在其上运行函数,但没有任何反应。我该如何处理我在这里提出的问题?

0 个答案:

没有答案