使用更改变量在 R 中循环写入和命名文件

Loop in R using changing variable to write and name files

我正在尝试在 R 中创建一个循环,该循环读取我导入的 netcdf 文件的每日值并将它们转换为年度总和,然后为每年创建一个栅格。我已将 netcdf 转换为数组 - 在下面的代码中将其命名为 Biased_corrected.array。我不确定如何在我的文件名中包含变量 'year',因为它随着循环的每次迭代而变化。我试过使用粘贴,但这似乎是它失败的地方。有什么建议吗?

# read in file specifying which days correspond to years
YearsDays <- read.csv("Data\Years.csv") # a df with 49 obs. of 3 variables (year, start day, and end day

YearsDays[1,2:3]  #returns 1 and 366 (the days for year 1972)
YearsDays[2,2:3]  #returns 367 and 731 (the days for year 1973)
YearsDays[1,1] #returns 1972
YearsDays[2,1] #returns 1973

counter <- 1
startyear <- YearsDays[1,1]
year <- startyear

while(year < 2021){
  #set variables to loop through
  startday <- YearsDays[counter,2]
  endday <- YearsDays[counter,3]

  BC_rain.slice <- Biased_corrected.array[,,startday:endday]
  paste(year, "_Annual_rain") <- apply(BC_rain.slice, c(1,2), sum)
  
  #save data in a raster
  paste(year, "_rain_r") <- raster(t(paste(year, "_Annual_Rain"), xmn=min(x), xmx=max(x), ymn=min(y), ymx=max(y), crs=WGS84)
  
  
  # move on to next year
  counter <- counter + 1
  year <- 1971 + counter
}

编辑:任何感兴趣的人的工作代码:

YearsDays <- read.csv("Data\Years.csv") # a df with 49 obs. of 3 variables (year, start day, and end day

for (idx in seq(nrow(YearsDays))){
  
  #set variables to loop through
  year <- YearsDays[idx,1]
  startday <- YearsDays[idx,2]
  endday <- YearsDays[idx,3]

  BC_rain.slice <- Biased_corrected.array[,,startday:endday]
  assign(paste(year, "_Annual_rain"),apply(BC_rain.slice, c(1,2), sum))
  annual_rain <- apply(BC_rain.slice, c(1,2), sum)
  
  #save data in a raster
  assign(paste(year, "_rain_r"),raster(t(annual_rain), xmn=min(x), xmx=max(x), ymn=min(y), ymx=max(y), crs=WGS84))
         
}

您不能使用 paste 创建您列出的变量名。您可以将其包含在 assigneval 中,但将结果存储在数据框中可能更容易。以下是我认为您要实现的目标的示例。我还用多年来迭代的 for 循环替换了您的 while 循环和计数器:

YearsDays <- read.csv("Data\Years.csv") # a df with 49 obs. of 3 variables (year, start day, and end day

output <- data.frame(year = YearsDays[,1], rain_r = NA)

for (idx in seq(nrow(YearsDays))){
  
  #set variables to loop through
  year <- YearsDays[idx,1]
  startday <- YearsDays[idx,2]
  endday <- YearsDays[idx,3]
  
  BC_rain.slice <- Biased_corrected.array[,,startday:endday]
  annual_rain <- apply(BC_rain.slice, c(1,2), sum)
  
  #save data in a raster
  output$rain_r[output$year == year] <- raster(t(annual_rain, xmn=min(x), xmx=max(x), ymn=min(y), ymx=max(y), crs=WGS84))

}

更换你的零件如何

paste(year, "_Annual_rain") <- apply(BC_rain.slice, c(1,2), sum)
  
#save data in a raster
paste(year, "_rain_r") <- raster(t(paste(year, "_Annual_Rain"), xmn=min(x), xmx=max(x), ymn=min(y), ymx=max(y), crs=WGS84)

txt <- paste0(year, "_Annual_rain <- apply(BC_rain.slice, c(1,2), sum)")
eval(parse(text = txt))

# save data in a raster
txt <- paste0(year, "_rain_r <- raster(t(", year, "_Annual_Rain), xmn=min(x), xmx=max(x), ymn=min(y), ymx=max(y), crs=WGS84)")
eval(parse(text = txt))