Reputation: 1114
R newbie here: I have seen multiple posts about looping write csv, but none where it inputs dataframes (not lists of dataframes) and loops to write a csv. I would like to loop through all dataframes, and create one csv per dataframe matching the dataframe name.
df1 <- data.frame(
var1 = sample(1:10, 6, replace = TRUE)
, var2 = sample(LETTERS[1:2], 6, replace = TRUE)
, theday = c(1,1,2,2,3,3)
)
df2 <- data.frame(
var1 = sample(1:10, 6, replace = TRUE)
, var2 = sample(LETTERS[1:2], 6, replace = TRUE)
, theday = c(1,1,2,2,3,3)
)
I have a character list with the names of the dataframes, but the data itself lives in the dataframes.
temp <- list("df1", "df2")
Output should have the data within a csv labeled 'df1.csv' and df2.csv I would think it would be something like this:
for (i in 1:length(temp)) write.csv(temp[i])
But this instead writes to the console and does perform write csv. Ideas?!
Upvotes: 0
Views: 1251
Reputation: 31171
As @Roland comment, you should loop over your list (with lapply
for example) and use get
and write.csv
:
lapply(temp, function(u) write.csv(get(u), file=u))
To store your data.frame
in a list you can do:
Filter(function(u) class(get(u))=='data.frame', ls())
Upvotes: 2