Home > Mobile >  How to save a large list containing multiple dataframes as individual csvs based on original file na
How to save a large list containing multiple dataframes as individual csvs based on original file na

Time:11-19

I have read in a list of files from a folder:

files <- list.files("E:new data/Depth and Temp")
allFiles.list <- lapply(files, read.table, sep = '\t')

and then applied a set of functions to the files that have been read in which works fine:

load_file <- function(files) {
  tab_file <- read.table(files, header = TRUE)
  tab_file$Date.Time <- as_datetime(tab_file$Time)
  tab_file$Date.Time <- tab_file$Date.Time   hours(9)
  setnames(tab_file, old = c('External.Temperature','Corrected.Depth.Channel'), new = c('Temp','Depth'))
  
  tab_file
}

list_of_files = list.files(pattern="*.tab")

data <- lapply(X = list_of_files, FUN = load_file)

I now have a large list containing the individual files as dataframes in R: Print screen

but am having a difficult time saving them as a new file. I would like the new file to be the same name is the previous file, but saved as a csv.

For example the current names:

144881.tab
144883_2.tab
156889.tab
156889_2.tab

and I would like them saved as:

144881.csv
144883_2.csv
156889.csv
156889_2.csv

I thought this would be relatively straight forward (and I am sure it is) but after a couple hours of internet searches I am still unable to find what I am looking for.

Note: I only supplied a small screenshot of my data (with 2 examples), but I have over 25 files in this folder so I am hoping to use the previous file name to avoid having to retype them all manually. Thank you in advance!

CodePudding user response:

you can try:

   filenames <- list.files(pattern="*.tab")
    file_prefix <- filenames |> stringr::str_extract("[:graph:]{1,1000}(?=\\.)")
    names(data) <- file_prefix
    file_prefix |> purrr::map(~write.csv(x = data[[.x]], file = paste0(.x, ".csv")))

if you have an older version of R you can use magrittrs %>% instead of |>.

  • Related