【问题标题】:Looping through files, NetCDF operations循环文件,NetCDF 操作
【发布时间】:2018-09-07 16:20:57
【问题描述】:

我正在尝试为数百个 NetCDF 文件执行以下代码,并将每个文件的此代码的结果组合在一起。

  library(raster)
  b <- brick('CA.195001.nc')
  be <- crop(b, extent(-177.0170, -117.2690, 32.7191, 32.9753)) 
  a <- aggregate(be, dim(be)[2:1], na.rm=TRUE)
  v <- values(a)

  #get date
  date <- getZ(be)

  df <- data.frame(date=date, prec=t(v)) 
  rownames(df) <- c()
  df


  df$date<- as.Date(df$date, "%m/%d/%Y") #Add dates
  df$year <- as.numeric(format(df$date, format = "%Y"))
  df$month <- as.numeric(format(df$date, format = "%m"))
  df$day <- as.numeric(format(df$date, format = "%d"))

我对循环比较陌生,并没有找到太多有用的指导。以下有助于识别文件,但我不太确定如何循环执行上述操作:

files <- list.files(path="mypath", pattern="*.nc", full.names=T, 
recursive=FALSE)
lapply(files, function(x) { 
}

谢谢!

【问题讨论】:

    标签: r loops netcdf


    【解决方案1】:

    您可以将代码放入一个函数中,然后使用 lapplypurrr:map_df 将该函数应用于所有 NetCDF 文件

    library(raster)
    
    read_ncdf <- function(input_NetCDF_file) {
      b  <- brick(input_NetCDF_file)
      be <- crop(b, extent(-177.0170, -117.2690, 32.7191, 32.9753)) 
      a  <- aggregate(be, dim(be)[2:1], na.rm=TRUE)
      v  <- values(a)
    
      #get date
      date <- getZ(be)
    
      df <- data.frame(date=date, prec=t(v)) 
      rownames(df) <- c()
    
      df$date<- as.Date(df$date, "%m/%d/%Y") #Add dates
      df$year <- as.numeric(format(df$date, format = "%Y"))
      df$month <- as.numeric(format(df$date, format = "%m"))
      df$day <- as.numeric(format(df$date, format = "%d"))
    
      return(df)
    }
    

    列出mypath中的所有NetCDF文件

    files <- list.files(path = "mypath", pattern = "\\.nc$", full.names = TRUE, 
                    recursive = FALSE)
    

    使用lapply

    result <- lapply(files, function(x) { read_ncdf(x) })
    # rbind all together 
    result_df <- do.call("rbind", result) 
    

    使用purrr::map_df

    library(tidyverse)
    # Loop through all the files using map_df, read data 
    # and create a FileName column to store filenames
    # Then clean up filename: remove file path and extension
    result_purrr <- files %>%
      purrr::set_names(nm = (basename(.) %>% tools::file_path_sans_ext())) %>%
      purrr::map_df(read_ncdf, .id = "FileName") 
    

    【讨论】:

    • 非常感谢!这正是我想要做的。
    • 你在哪里让它得到回答?
    猜你喜欢
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2014-04-12
    • 2014-01-03
    • 1970-01-01
    相关资源
    最近更新 更多