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?
A few of things.
myList doesn't have any names, so you aren't actually naming your files.myList names, you would do better to index along the names than along the listdf 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"))
}
                        You can also use mapply:
myList <- list(diamonds = diamonds, 
               cars = cars)
mapply(write.csv, myList, file=paste0(names(myList), '.csv'))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With