如何使用文本文件中的数据?

How to use data in a text file?

给定三个栅格,我需要从文本文件 smoke.

中提取对应于 u(行)= 5 和 c(列)的值
smoke <- matrix(c(5, 4, 2, 9, 2, 2), ncol=2, byrow=TRUE)

我使用的函数是:

library(raster)
r <- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))

func <- function(c, u, sit){
  rasters <- mget(c('r', paste0('r', 1:2)))
  x <- sapply(rasters, function(x) getValues(x, c)[u])
  y <- sapply(rasters, function(x) getValues(x, u)[c])
  g <- data.frame(y, x)
  write.table(g, paste0("res_", sit, u, "_", c, ".txt"))
}

以下是我如何使用该函数提取对应于 smoke 中的 cu 的值:

res <- lapply(split(smoke[,c('c', 'u', 'sit')], 1:nrow(smoke)), 
              FUN=function(x) func(c=x[1], u=x[2], sit=x[3]))

我收到此错误:error: value for ‘r’ not found

默认情况下,mget 仅在调用它的环境中查找对象 rr1r2,但在您的情况下,那些对象在全局环境中。您可以将 inherits=TRUE 添加到 mget 调用,这将强制它继续在父环境中查找,或者使用 envir=.GlobalEnv 指定要查找的环境。

不过,您还有其他一些问题。

首先,r1r2 在您的示例中不存在。

其次,split产生的列表是一个数据框列表,你需要在你的函数中对它们进行相应的索引。这意味着使用 $ 符号(例如 x$c)、双括号(例如 x[[1]])或使用逗号(例如 x[, 1])。

实现所有这些,你应该有这样的东西:

func <- function(c, u, sit) {
  rasters <- mget(c('r', paste0('r', 1:2)), envir=.GlobalEnv)
  x <- sapply(rasters, function(x) getValues(x, c)[u])
  y <- sapply(rasters, function(x) getValues(x, u)[c])
  g <- data.frame(y, x)
  write.table(g, paste0("res_", sit, u, "_", c, ".txt"))
}

library(raster)
res <- lapply(split(smoke[, c('c', 'u', 'sit')], 1:nrow(smoke)), 
              function(x) func(c=x[[1]], u=x[[2]], sit=x[[3]]))

最后,res 将只是一个 NULL 值的列表,因为您的函数 return 是 write.table 的值,即 NULL .如果您希望 func 到 return g,则在函数中添加最后一行,简单地读取 g(或者明确地,return(g))。

我不确定你的小例子在多大程度上反映了你的真实数据,但你可能会更有效地处理这个问题 - 请参阅 ?extract?cellFromRowCol?stack,因为例如。