0

I have multiple dataframes of different dimensions that follow the naming scheme "data_x". I want to export them as .csv-files following a similar naming scheme. I found this answer but it relates to dataframes of the same dimensions. This is what I tried:

my_list <- (list = ls()[grep("^data", ls())])

data_list <- as.list(my_list)

bindFn <- function(i, data_list){
  sapply(data_list, '[[', i)
}

for(i in names(data_list)) write.csv(bindFn(i, data_list), paste0("data_",i, ".csv"), row.names=F)
ab0rt
  • 69
  • 6

2 Answers2

3

ls() has pattern argument to get the object name based on specific pattern in the data. You may try -

my_list <- ls(pattern = '^data')

purrr::imap(mget(my_list),
             ~write.csv(.x, sprintf('data_%s.csv', .y), row.names = FALSE))

To keep it completely in base R -

tmp <- mget(my_list)
Map(function(x, y) write.csv(x, y, row.names = FALSE), tmp, 
                   sprintf('data_%s.csv', names(tmp)))

where mget returns a named list of dataframes.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1
purrr::walk(my_list, ~ write_csv2(get(.), str_c(., ".csv")))
crestor
  • 1,388
  • 8
  • 21