[英]Extracting 3D netcdf variable from lists within nested loop in R
Say I have 10 model configurations of n timesteps for 3 different sites, producing a total 30 netcdf files I want to open and manipulate. 假设我有3个不同站点的n个时间步长的10个模型配置,总共生成了30个我要打开和操作的netcdf文件。 I can open the 30 files such as
我可以打开30个文件,例如
require(ncdf4)
allfiles= list()
nmod=10
nsites=3
for (i in 1:nmod) {
allfiles[[i]] = list(nc_open(paste0('Model',i,'siteA.nc')),
nc_open(paste0('Model',i,'siteB.nc')),
nc_open(paste0('Model',i,'siteC.nc')))
}
When querying the class of what was opened, I have 当查询打开什么的类时,我有
class(allfiles)
类(所有文件)
[1] "list"
[1]“清单”
class(allfiles[[1]][[1]])
类(所有文件[[1]] [[1]])
[1] "ncdf4"
[1]“ ncdf4”
as expected. 如预期的那样。 Now what I would like to do is extract the values from a variable in the files such that
现在我要做的是从文件中的变量中提取值,这样
var=list()
for (i in 1:nmod) {
for (j in 1:nsites) {
var[[i]][[j]] <- ncvar_get(allfiles[[i]][[j]],"var1")
nc_close(allfiles[[i]][[j]])
}}
but I get this error message: 但我收到此错误消息:
`Error in *tmp*[[i]] : subscript out of bounds`
If I try 如果我尝试
var[[i]] <- ncvar_get(allfiles[[i]][[j]],"var1")
it (understandbly) only produces a list of 10 model configurations at one site, ie var[[1]][[1]][1]
prints out the value of the variable at model configuration 1, site A, timestep 1 but var[[1]][[2]]
doesn't exist. 它(理解)仅在一个站点上生成10个模型配置的列表,即
var[[1]][[1]][1]
在模型配置1,站点A,时间步1处打印出变量的值,但var[[1]][[2]]
不存在。 How can I declare var
in the above loop so that it contains all the values for all models, all sites and all timesteps (eg for var[[1]][[2]][1]
to exist)? 如何在上面的循环中声明
var
,以便它包含所有模型,所有站点和所有时间步的所有值(例如var[[1]][[2]][1]
存在)?
In your original version where the error occurs, in the first inner loop, you try to do something: var[[1]][[1]] <- something
, but var[[1]]
doesn't exist, and R
doesn't know what to do, so I guess the following thing should work, you set var[i] <- list()
before you do var[[i]][[j]] <- something
: 在发生错误的原始版本中,在第一个内部循环中,您尝试执行以下操作:
var[[1]][[1]] <- something
,但是var[[1]]
不存在,并且R
不知道该怎么办,所以我猜下面的事情应该起作用,您在执行var[[i]][[j]] <- something
之前先设置var[i] <- list()
:
var=list()
for (i in 1:nmod) {
var[i] <- list()
for (j in 1:nsites) {
var[[i]][[j]] <- ncvar_get(allfiles[[i]][[j]],"var1")
nc_close(allfiles[[i]][[j]])
}
}
For example, if you do: 例如,如果您这样做:
var <- list()
for (i in 1:10) {
for (j in 1:10) {
var[[i]][[j]] <- 1
}
}
Then the same error happens. 然后发生相同的错误。 But if you set
var[[i]] <- list()
before carrying out the inner loop like this: 但是,如果您在执行内部循环之前设置
var[[i]] <- list()
,如下所示:
var <- list()
for (i in 1:10) {
var[[i]] <- list()
for (j in 1:10) {
var[[i]][[j]] <- 1
}
}
Then the problem will be solved. 然后问题就解决了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.