我想使用循环提取365个netcdf文件

时间:2019-07-02 18:58:49

标签: r loops netcdf

我在R中有一个代码可以提取单个netcdf文件的数据。但是,我有365个netcdf文件。我想使用循环从所有这些文件中提取数据,并将它们写入单独的csv文件。

我已经为单个文件准备了代码。需要多个netcdf文件的帮助。

library(ncdf4)
ncname = "ESACCI-L3S_SOILMOISTURE-SSMV-MERGED-19781102000000-fv00.1"
ncfname = paste(ncname, ".nc", sep = "")
dname = "sm"
ncin = nc_open(ncfname)
print(ncin)
lon <- ncvar_get(ncin, "lon")
nlon <- dim(lon)
head(lon)
lat <- ncvar_get(ncin, "lat", verbose = F)
nlat <- dim(lat)
head(lat)
print(c(nlon, nlat))
sm_array <- ncvar_get(ncin,dname)
dlname <- ncatt_get(ncin,dname,"long_name")
dunits <- ncatt_get(ncin,dname,"units")
fillvalue <- ncatt_get(ncin,dname,"_FillValue")
dim(sm_array)
ls()
m <- 1
sm.slice <- sm_array[,]
sm.vec <- as.vector(sm.slice)
length(sm.vec)
lonlat <- expand.grid(lon, lat)
sm.df01 <- data.frame(cbind(lonlat, sm.vec))
names(sm.df01) <- c("lon", "lat", paste(dname, as.character(m), sep = "_"))
head(na.omit(sm.df01), 20)
csvfile <- "sm_trial2.csv"
write.table(na.omit(sm.df01), csvfile, row.names = FALSE, sep = ",")

我需要为365个netcdf文件修改此代码。

1 个答案:

答案 0 :(得分:3)

我建议将您的代码包装到一个函数中,并像这样使用lapply()

library(ncdf4)

my_read_function <- function(ncname) {
  ncfname = ncname
  dname = "sm"
  ncin = nc_open(ncfname)
  print(ncin)
  lon <- ncvar_get(ncin, "lon")
  nlon <- dim(lon)
  head(lon)
  lat <- ncvar_get(ncin, "lat", verbose = F)
  nlat <- dim(lat)
  head(lat)
  print(c(nlon, nlat))
  sm_array <- ncvar_get(ncin,dname)
  dlname <- ncatt_get(ncin,dname,"long_name")
  dunits <- ncatt_get(ncin,dname,"units")
  fillvalue <- ncatt_get(ncin,dname,"_FillValue")
  dim(sm_array)
  ls()
  m <- 1
  sm.slice <- sm_array[,]
  sm.vec <- as.vector(sm.slice)
  length(sm.vec)
  lonlat <- expand.grid(lon, lat)
  sm.df01 <- data.frame(cbind(lonlat, sm.vec))
  names(sm.df01) <- c("lon", "lat", paste(dname, as.character(m), sep = "_"))
  head(na.omit(sm.df01), 20)
  csvfile <- paste0(ncname, ".csv")  ## change the outfile name appropriately
  write.table(na.omit(sm.df01), csvfile, row.names = FALSE, sep = ",")
}

my_files <- list.files("/path/to/all/those/files")
lapply(my_files, my_read_function)