Search code examples
rlistloopscsvexport-to-csv

How to process a list of .csv dataframe


Sorry for newbie question here, What happened is I wrote a series of code to process one .csv data frame.

Here is what code (sample version)looks like:

MyFile <- read.csv(tk_choose.files(caption = "Choose CSV files from directory",),header = TRUE)%>% # 
 Select Input CSV Data
 transmute(A)%>% 
 summarise_all(sum,)%>%
 write.csv(file = choose.files()) # Output As CSV File)

and here is what output looks like in the Output CSV file:

enter image description here

But now I need to apply those series of code to a list of .csv data instead of one.

I managed to use the code:

temp = tk_choose.files(caption = "Choose CSV files from directory",)
myfiles = lapply(temp, read.delim)

to import those .csv files as a list, but is there any way that I can apply the same code (ie.

transmute(A)%>% 
summarise_all(sum,)%>%

) to all the .csv files in the list and combine the result together? (ie.

            A
file1   658839755
file2   1541654313
file3   4643213843

)

Thank you


Solution

  • You can use lapply/map over myfiles and apply the same code to each file.

    library(dplyr)
    purrr::map(myfiles, ~.x %>% transmute(A)%>% 
                         summarise_all(sum) %>%
                         write.csv(file = choose.files())) 
    

    However, this might be simpler

    purrr::map(myfiles, ~.x %>% summarise(A = sum(A)) %>% 
                          write.csv(file = choose.files())