Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

r - How do I write multiple CSV files from a list of data frames?

I have a list with two data frames. I want to loop thru the list and write a CSV for each data frame and name it after the data frame name.

library(ggplot2)
myList <- list(diamonds, cars)
for(i in mylist){
  write.csv(df, paste0(names(myList[i]),".csv"))
}

But this only outputs one CSV file names .csv with data from cars.

How do I fix this so I have two CSVs named diamonds.csv and cars.csv with the correct data in each?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A few of things.

  1. myList doesn't have any names, so you aren't actually naming your files.
  2. Once you give myList names, you would do better to index along the names than along the list
  3. You use df in your for loop, but that isn't defined anywhere.

This should work (untested)

myList <- list(diamonds = diamonds, 
               cars = cars)
for(i in names(mylist)){
  write.csv(myList[[i]], paste0(i,".csv"))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...