我试图通过for循环在R中附加几个数据帧,但以下代码不起作用:
rm(list = ls())
# ------------------------------------------------------------------------------
# Libraries
# ------------------------------------------------------------------------------
library("dplyr")
library("readxl")
date <- "202203"
startwave <- 2010
endwave <- 2018
# ------------------------------------------------------------------------------
# Paths and Files
# ------------------------------------------------------------------------------
dell <- 1
if (dell == 1) {
computer <- "C:/Users/jj22684/"
} else {
computer <- "C:/Users/lenovo/"
}
Main_path <- paste(computer, "Dropbox/DATA/REGCON", sep = "")
raw_path <- paste(computer, "Dropbox/DATA/REGCON/RAW files", sep = "")
# REGCON_PATHS
# ------------------------------------------------------------------------------
# Import
# ------------------------------------------------------------------------------
for (y in endwave:startwave) {
FIRMCAtemp <- read_excel(paste(raw_path, "/Datos_totales_", y, "_REGCON.xlsx", sep = ""))
assign(toString(y),y)
FIRMCAtemp$year <- y
assign(paste("FIRMCA", y, sep = ""),FIRMCAtemp)
}
for (y in startwave:endwave) {
FIRMCAtemp <- rbind(FIRMCAtemp,paste("FIRMCA", y, sep = ""))
}
我也试过使用sym()函数,它也不奏效。
如果有人能给我一些建议,我将非常感激。
基米-雷克南鲁本
一种选择是使用lapply
将XL文件读取到列表中,并使用dplyr::bind_rows
将它们绑定到一个df中。
使用一些虚假的示例数据:
# Create exammple files
rawpath <- tempdir()
writexl::write_xlsx(mtcars, file.path(rawpath, "Datos_totales_2010_REGCON.xlsx"))
writexl::write_xlsx(mtcars, file.path(rawpath, "Datos_totales_2011_REGCON.xlsx"))
startwave <- 2010
endwave <- 2011
lapply(endwave:startwave, function(y) {
x <- readxl::read_excel(paste0(rawpath, "/Datos_totales_", y, "_REGCON.xlsx"))
x$year <- y
x
}) |>
dplyr::bind_rows()
#> # A tibble: 64 × 12
#> mpg cyl disp hp drat wt qsec vs am gear carb year
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int>
#> 1 21 6 160 110 3.9 2.62 16.5 0 1 4 4 2011
#> 2 21 6 160 110 3.9 2.88 17.0 0 1 4 4 2011
#> 3 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1 2011
#> 4 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1 2011
#> 5 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2 2011
#> 6 18.1 6 225 105 2.76 3.46 20.2 1 0 3 1 2011
#> 7 14.3 8 360 245 3.21 3.57 15.8 0 0 3 4 2011
#> 8 24.4 4 147. 62 3.69 3.19 20 1 0 4 2 2011
#> 9 22.8 4 141. 95 3.92 3.15 22.9 1 0 4 2 2011
#> 10 19.2 6 168. 123 3.92 3.44 18.3 1 0 4 4 2011
#> # … with 54 more rows