2017-07-14 48 views
2

我有2个netCDF文件(每个.nc文件有4个变量:敏感,感染,恢复和居住,每个变量的尺寸为64 x 88)。我想将这两个文件合并到一个单独的netCDF文件中,这样合并的文件将分别堆叠。从2个文件中感受敏感,从2个文件中感染,从2个文件中恢复,并从2个文件中居住。合并NetCDF文件在R

这里有2个文件(firstsecond

谁能帮我这个好吗?

由于提前, 阿肖克

+0

你是什么意思与“分开堆叠”? – Bart

+0

新变量的尺寸应该是“(64,176)”还是“(128,88)”? – JanLauGe

+0

“分开堆叠”我的意思是把数组放在另一个之上。例如,对于时间0001而言,从文件1易受影响,对于时间为0001的易感文件和用于时间0002的易感文件。有一个名为Panoply的免费工具,让您创建一个动画,如果netcdf文件具有变量的时间上下文(在我的情况下为敏感,感染,恢复)。 –

回答

2

ncdf4包会做你想要做的事。看看下面的代码,仅为一个变量的例子。

#install.packages('ncdf4') 
library(ncdf4) 

file1 <- nc_open('England_aggr_GPW4_2000_0001.nc') 
file2 <- nc_open('England_aggr_GPW4_2000_0002.nc') 

# Just for one variable for now 
dat_new <- cbind(
    ncvar_get(file1, 'Susceptible'), 
    ncvar_get(file2, 'Susceptible')) 
dim(dat_new) 
var <- file1$var['Susceptible']$Susceptible 

# Create a new file 
file_new3 <- nc_create(
    filename = 'England_aggr_GPW4_2000_new.nc', 
    # We need to define the variables here 
    vars = ncvar_def(
    name = 'Susceptible', 
    units = var$units, 
    dim = dim(dat_new))) 

# And write to it 
ncvar_put(
    nc = file_new, 
    varid = 'Susceptible', 
    vals = dat_new) 

# Finally, close the file 
nc_close(file_new) 

更新: 另一种方法是使用光栅包,如下所示。我没有弄清楚如何制作4D光栅堆栈,所以我将每个变量的数据分成一个NCDF文件。这对你有用吗?

#install.packages('ncdf4') 
library(ncdf4) 
library(raster) 

var_names <- c('Susceptible', 'Infected', 'Recovered', 'Inhabitable') 

for (var_name in var_names) { 

    # Create raster stack 
    x <- stack(
    raster('England_aggr_GPW4_2000_0001.nc', varname = var_name), 
    raster('England_aggr_GPW4_2000_0002.nc', varname = var_name)) 

    # Name each layer 
    names(x) <- c('01', '02') 

    writeRaster(x = x, 
       filename = paste0(var_name, '_out.nc'), 
       overwrite = TRUE, 
       format = 'CDF') 
} 
+0

当我运行一行file_new时出现以下错误: [1]“错误,传入的变量具有不等于ncdim4的昏暗!” [1]在ncvar_def 错误(名称=“易感”,单位=变量$单位,暗淡=暗淡(dat_new))“处理变量易感的暗淡数1时发生错误”: 此暗淡具有类:整数 而不是cbind()我想知道我们是否可以保留易受影响的维度,但我想要一个易受影响的[[1]]为file1,易感[[2]]为file2等列表 –

+0

我会尝试明天再看看这个 – JanLauGe

+0

更新了我的回答,展示了一个使用'raster'包的替代方法。让我知道这是否适合你 – JanLauGe