简体   繁体   English

如何在R中单独合并netcdf文件?

[英]How to merge netcdf files separately in R?

I am a user of R and would like some help in the following: I have two netcdf files (each of dimensions 30x30x365) and one more with 30x30x366. 我是R的用户,并且在以下方面需要帮助:我有两个netcdf文件(每个文件的尺寸为30x30x365),另一个为30x30x366。 These 3 files contain a year's worth of daily data, where the last dimension refers to the time dimension. 这3个文件包含一年的每日数据,其中最后一个维度是时间维度。 I wanted to combine them separately ie I wanted the output file to contain 30x30x1096. 我想将它们分开组合,即我希望输出文件包含30x30x1096。

Note: I have seen a similar question but the output results in an average (ie 30x30x3) which I do not want. 注意:我看到了类似的问题,但是输出结果导致了我不想要的平均值(即30x30x3)。

from the comment I see below you seem to want to merge 3 files in the time dimension. 从下面我看到的注释中,您似乎想在时间维度上合并3个文件。 As an alternative to R, you could do this quickly from the command line using cdo (climate data operators): 作为R的替代方法,您可以使用cdo(气候数据运算符)从命令行快速完成此操作:

cdo mergetime file1.nc file2.nc file3.nc mergedfile.nc

or using wildcards: 或使用通配符:

cdo mergetime file?.nc mergedfile.nc

cdo is easy to install under ubuntu: cdo很容易在ubuntu下安装:

sudo apt install cdo 

Without knowing exactly what dimensions and variables you have, this may be enough to get you started: 不知道确切的尺寸和变量,这足以让您入门:

library(ncdf4)

output_data <- array(dim = c(30, 30, 1096))
files <- c('file1.nc', 'file2.nc', 'file3.nc')
days <- c(365, 365, 366)

# Open each file and add it to the final output array
for (i in seq_along(files)) {
    nc <- nc_open(files[i])
    input_arr <- ncvar_get(nc, varid='var_name')
    nc_close(nc)

    # Calculate the indices where each file's data should go
    if (i > 1) {
        day_idx <- (1:days[i]) + sum(days[1:(i-1)])
    } else {
        day_idx <- 1:days[i]
    }

    output_data[ , , day_idx] <- input_arr
}

# Write out output_data to a NetCDF. How exactly this should be done depends on what
# dimensions and variables you have.

# See here for more:
#   https://publicwiki.deltares.nl/display/OET/Creating+a+netCDF+file+with+R

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM