Home > Back-end >  Write_csv for a list of csv.files mantaining original file names
Write_csv for a list of csv.files mantaining original file names

Time:07-27

I have a df list (df_list) and i want a tydiverse approach to write all csv files from my list while mantaining their original file names.

So far i did:

df = dir(pattern = "\\.csv$", full.names = TRUE)  
df_list = vector("list",length(df))
  
for(i in seq_along(networks)) 
{   
  df_list[[i]] = read.csv(df[[i]], sep = ";") 

}

imap(df_list, ~write_csv(.x, paste0(.y,".csv")))

my current output is:

1.csv; 2.csv; 3.csv ...

CodePudding user response:

The below will read in a set of files from an example directory, do apply a function to those files, then save the files with the exact same names.

library(purrr)
library(dplyr)

# Create example directory with example .csv files
dir.create(path = "example")
data.frame(x1 = letters) %>% write.csv(., file = "example/example1.csv")
data.frame(x2 = 1:20) %>% write.csv(., file = "example/example2.csv")

# Get relative paths of all .csv files in the example subdirectory
path_list <- list.files(pattern = "example.*csv", recursive = TRUE) %>%
  as.list()

# Read every file into list
file_list <- path_list %>%
  map(~ read.csv(.x, sep = ","))

# Do something to the data
file_list_updated <- file_list %>%
  map( ~ .x %>% mutate(foo = 5))

# Write the updated files to the old file names
map2(.x = file_list_updated,
     .y = path_list,
     ~ write.csv(x = .x, file = .y))
  • Related