【发布时间】:2021-02-03 15:15:39
【问题描述】:
我有多个名为“2003_BY_HR.xls 的副本”、“2004_BY_HR.xls 的副本”...“2010_BY_HR.xls 的副本”等的 excel 文件。文件命名是唯一的,名称中只有年份更改。工作表也具有相同的名称。我正在使用 readxl 包来读取数据。我只需更改年份即可读取和输出每个文件的数据。我想自动有效地实现这一点,而不是手动更改文件名并重新运行脚本。我的有效脚本如下所示。
setwd("Data")
library(readxl)
# I read in the first file
dataf<-"Copy of 2003_BY_HR.xls"
ICA <- read_excel(dataf,
sheet = "ICA_HR_2003")
ET <- read_excel(dataf,
sheet = "ET_HR_2003", na ="0")
# I read the data from first sheet and retrieve variable of interest
Grain_ICA <- ICA$`Grain ICA`
Rice_ICA <- ICA$`Rice ICA`
Cotton_ICA <- ICA$`Cotton ICA`
# I read the data from second sheet and retrieve variable of interest
Grain_ET <-ET$`Grain ET WA`
Rice_ET <-ET$`Rice ET WA`
Cotton_ET <-ET$`Cotton ET WA`
# I compute the results and save to a single file by appending
ET_grain <- sum(Grain_ICA * Grain_ET * 1000, na.rm=T)
ET_rice <- sum(Rice_ICA * Rice_ET *1000, na.rm=T)
ET_cotton <- sum(Cotton_ICA * Cotton_ET *1000, na.rm=T)
result <- data.frame( ET_grain,ET_rice,ET_cotton)
colnames(result) <- c("Grain","Rice","Cotton")
write.table(result, file = "ET.csv", append=T, sep=',',
row.names=F,
col.names=F)
【问题讨论】:
标签: r excel loops append multiple-file-upload