I have a number of data.frames, with names apple, banana, and coffee. I want to create, and then export, new dataframes in a for-loop corresponding to each one, call them apple_new, banana_new, and coffee_new.
I have in mind something along the lines of this pseudo-code
for (x in c("apple", "banana", "coffee")) { newdf_name <- paste0(x, "_new") #insert some magical function here that: # (1) creates a new data frame as a copy of the dataframe {x} # (2) calls that new dataframe {x}_new, # i.e., the string contents of newdf_name # become the name of a new variable write.csv(x_new) } The basic problem with the above is that at different points in this loop, I want x to refer to either a string "apple" or the data frame named apple (and analogously, I want to create a data frame named apple_new such that the starting point for that data frame is apple_new <- apple.
I'm assuming there must be a way for R to take a string input, tell R that it refers to a variable name, and then perform operations on that variable.
The closest thing I've found is to create a list of named list of data frames so that that I can refer to either the string or the variable as needed. That is:
newlist <- list(apple = apple, banana = banana, coffee = coffee) for (i in 1:length(newlist)) { #create new dataframe based on the original df <- newlist[[i]] #export: outfile <- paste0(names(newlist[i]),"_new.csv") write.csv(df, outfile) } This solution is sub-optimal because (a) I have to hard-code the new list of names/corresponding data frames, and (b) it doesn't actually create the desired new data frames apple_new, banana_new, etc.
R-like). Currently it appears like you want to rename files (on disk) and collect them asdata.frames in alist(in your IDE of choice). Am I correct?