I have a loop that reads in a set of files, assigning the name of each object dynamically using the file name. Each file is named "timeseries_" and then a year.
library(haven)
library(dplyr)
library(stringr)
files <- list.files(path="data-raw/timeseries", pattern="*.dta", full.names=TRUE, recursive=FALSE)
for(file in files){
assign(paste0("timeseries_",str_extract(file, "([0-9]+)")), read_dta(file))
}
After reading in each file, I want the loop to save the object to an .rda file, but I'm having trouble referring to the variable that was just created. When I use as.name() I get an error:
files <- list.files(path="data-raw/timeseries", pattern="*.dta", full.names=TRUE, recursive=FALSE)
for(file in files){
assign(paste0("timeseries_",str_extract(file, "([0-9]+)")), read_dta(file))
save(as.name(paste0("timeseries_",str_extract(file, "([0-9]+)"))),
file=paste0("data/pilot_",str_extract(file, "([0-9]+)"), ".rda"), compress="xz")
}
Error in save(as.name(paste0("timeseries_", str_extract(file, "([0-9]+)"))), :
object ‘as.name(paste0("timeseries_", str_extract(file, "([0-9]+)")))’ not found
Is there a different way to refer to the just-created variable?