I want my code to accept the dataframes in a list one by one, so one by one I want to make the changes to them (add a variable sect), then save the dataframe, and move on to the next dataframe in the list. I tried to do this in the manner below, but I don't think it works!
setwd("C:\\Users\\datasets")
files = list.files(pattern="*.dta")
dflist <- list()
for (i in 1:length(files)){
dflist[[i]] <- read.dta13(files[i], nonint.factors = TRUE)
names(dflist) <- gsub("\\.dta$", "", list)
#This creates "sect" variable if it doesn't exist already.
if(!("sect" %in% colnames(dflist[[i]]))){
dflist[[i]]$sect <- "total"}
#Saving dataset
save.dta13(dflist[[i]], paste0(i, ".dta"))
}
Edit: It gives this error:
Error in as.character(x) :
cannot coerce type 'builtin' to vector of type 'character'`