Writing multiple data frames to CSV files using R
I used lapply to apply a function to a series of data frames:
data.cleaned <- lapply(data.list, shooter_cleaning)
Then, each of the resulting data frames in the list is tagged according to their topic number (for example, 100):
names(data.cleaned) <- subject.names
What I want to do is save each new dataframe as a separate CSV file based on its topic number. For example, for subject 100, I would like the .csv file to be marked as "100.csv" Usually for this (for one data frame) I would just write (where x is the data frame):
write.csv(x, "100.csv", row.names = F)
But obviously using this for my list of data frames will get you many copies of "100.csv", instead I would like the files to be unique based on their topic number. How can I (apply to?) Save each of these data frames to my own unique CSV file?
Here's a stand-alone example according to Richard's comments, but uses the datafile names in the list as the filenames for the CSV files:
# Create a list of n data frames
n <- 10
my_list <- lapply(1:n, function(i) data.frame(x = rnorm(10), y = rnorm(10)) )
# name the data frames
names(my_list) <- letters[1:n]
# save each new data frame as an individual .csv file based on its name
lapply(1:length(my_list), function(i) write.csv(my_list[[i]],
file = paste0(names(my_list[i]), ".csv"),
row.names = FALSE))
In case it helps: I had an environment with multiple data frames and only those data frames, and I wanted to output each data frame as a separate CSV file. With the help of Ben's answer and discovery, mget
I was able to do it with the following code:
for(i in 1:length(ls())) {
write.table(
mget(ls()[[i]]),
file = paste0(ls()[[i]], ".csv"),
sep = ";",
qmethod = "double",
row.names = FALSE)
}