I would like to export several dataframes as separate csv files to the working directory with a loop rather than writing out all of th names
##Sample data frame
employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))
d30 <- data.frame(employee, salary, startdate)
##Creating a few of the same name for illustrative purposes
d39 <- data.frame(employee, salary, startdate)
d40 <- data.frame(employee, salary, startdate)
for (list in c(d30,d39)){
write.csv(list, file="list.csv", row.names = FALSE)
}
Obviously I'm quite wrong. But I can't figure out how to do it.
Iterate over the data frame names. We assume all names start with d and are of length 3. Modify the pattern if not or directly set nms if you know them. We also make a second check that the names are data frames but you can omit that check if you are sure that there are no objects that are not data frames and have a name matching the pattern.
nms <- ls(pattern = "^d..$")
for(nm in nms) {
X <- get(nm)
if (is.data.frame(X)) {
filename <- paste0(nm, ".csv")
message("writing out ", filename)
write.csv(X, file = filename, row.names = FALSE)
}
}
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