I intend to mount a list of dataframe then use a loop structure to write each in a .csv file. Something like that:
for (i in myDataFramelist)
write.csv( ...)
I intend to mount a list of dataframe then use a loop structure to write each in a .csv file. Something like that:
for (i in myDataFramelist)
write.csv( ...)
Since you're working with a list and mention dplyr
, purrr
's walk
functions are well suited. Unlike map
, walk
expects to apply a function to each element of a list without returning or printing to the console, so it's a good choice for saving files. iwalk
takes both the list elements and the list elements' names, which is useful for creating file names. Here are a few ways to do it. For dummy data, I split the mpg
data frame and took the first 3 elements.
library(tidyverse)
df_list <- mpg %>% split(.$manufacturer) %>% `[`(1:3)
# makes files mpg_audi.csv, etc
iwalk(df_list, function(df, name) {
write_csv(df, sprintf("mpg_%s.csv", name))
})
purrr
functions let you use dot notation as a shorthand—for something more complex than this, I'd prefer writing out the function as above, just to be clear about what's going on, but in this case .x
is shorthand for each data frame and .y
is shorthand for each data frame's name.
# makes files mpg_audi_dot_notation.csv, etc
iwalk(df_list, ~write_csv(.x, sprintf("mpg_%s_dot_notation.csv", .y)))
If your list doesn't have names, you can instead use walk2
, which takes two arguments, and use the location in the list as the second argument.
names(df_list) <- NULL
# makes files mpg_1.csv, etc
walk2(df_list, 1:length(df_list), ~write_csv(.x, sprintf("mpg_%s.csv", .y)))
Created on 2018-06-16 by the reprex package (v0.2.0).
R is a highly vectorized language, so you usually don't need to use for
loops :
lapply(Filter(function(x) is.data.frame(get(x)), ls()),
function(x) write.csv(get(x), paste0(x, ".csv")))
Explanation:
lapply
as you're going to apply a function to a listls
gives all objects in envirnomentis.data.frame
will return TRUE if the object is a data.frameFilter
will select wich are TRUEwrite.csv
does, you pass get(x)
as the object to be saved, and make a name with the object's nameEven if it might not be the best way of doing it, I guess this example can make you understand a way through:
mat1<- matrix(1:9,3,3)
mat2<- matrix(1:16,4,4)
mylist <- list(mat1,mat2)
for( i in 1:length(mylist)){
name<- paste0("matrix",i) ## Write the name you want
write.csv(mylist[[i]], name) # Add the location where you want to store the file if so
}
Cheers !