Search code examples
rdataframesave

How to save data in global environment with same ending automatically with their names into a folder on PC?


I would like to save single dataframes with the same name they have in the environment automatically without writing the name for each dataframe itself in the code. How can I do that?

library(dplyr)
set.seed(94756)
Data_Date03.03.22Time10.23.45.xlsx <- matrix(sample(seq(-1,100, 0.11),70, replace = TRUE),ncol = 5) 
Data_Date03.03.22Time10.23.45.xlsx <- as.tibble(Data_Date03.03.22Time10.23.45.xlsx)

Data_Date03.03.22Time10.26.36.xlsx <- matrix(sample(seq(-1,100, 0.11),70, replace = TRUE),ncol = 5)  
Data_Date03.03.22Time10.26.36.xlsx <- as.tibble(Data_Date03.03.22Time10.26.36.xlsx)
Data_Date03.03.22Time10.26.36.xlsx[3,1] <- NA
Data_Date03.03.22Time10.26.36.xlsx[6,1] <- NA

Data_Date03.03.22Time10.27.12.xlsx <- matrix(sample(seq(-1,100, 0.11), 70,replace = TRUE),ncol = 5)  
Data_Date03.03.22Time10.27.12.xlsx <- as.tibble(Data_Date03.03.22Time10.27.12.xlsx)
Data_Date03.03.22Time10.27.12.xlsx[4,1] <- NA


data <- list(Data_Date03.03.22Time10.23.45.xlsx, Data_Date03.03.22Time10.26.36.xlsx, Data_Date03.03.22Time10.27.12.xlsx)

The result in my PC "save documents" folder should be: Data_Date03.03.22Time10.23.45.xlsx | Data_Date03.03.22Time10.26.36.xlsx | Data_Date03.03.22Time10.27.12.xlsx | ...as three single excel documents.

Thanks in advance!


Solution

  • This would write excel files in your working directory.

    purrr::imap(mget(ls(pattern = '^Data_Date')), writexl::write_xlsx)
    

    If you want to write it to specific folder, you can do -

    purrr::imap(mget(ls(pattern = '^Data_Date')), 
            ~writexl::write_xlsx(.x, paste0('/path/to/folder/', .y)))
    

    Explanation -

    ls with pattern returns names of the object in global environment which has the pattern in their name.

    ls(pattern = '^Data_Date')
    #[1] "Data_Date03.03.22Time10.23.45.xlsx" "Data_Date03.03.22Time10.26.36.xlsx"
    #[3] "Data_Date03.03.22Time10.27.12.xlsx"
    

    mget would create a named list of tibble. imap is used to write the tibbles to excel files where .x is the tibble whereas .y is name of the object.