Writing multiple data frames into .csv files using R

*爱你&永不变心* 提交于 2019-11-27 04:43:36
Ben

Here's a self-contained example along the lines of Richard's comment, but uses the names of the dataframes in the list as 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 this 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 discovering mget, I was able to do that 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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!