0

I would like to bring my dataframes within a list out of the list to have several dataframes at the end. Additionally I would like to give them automatically the name which they had before I read them into a list, with adding an ending name ".done" for example and write.table() back into my folder where the original data comes from for every dataframe.done in my environment. Here my example data

library(dplyr)
set.seed(94756)
mat1 <- matrix(sample(seq(-1,100, 0.11),50, replace = TRUE),ncol = 5) 
mat1 <- as_tibble(mat1)

mat2 <- matrix(sample(seq(-1,100, 0.11),50, replace = TRUE),ncol = 5)  
mat2 <- as_tibble(mat2)

mat3 <- matrix(sample(seq(-1,100, 0.11), 50,replace = TRUE),ncol = 5)  
mat3 <- as_tibble(mat3)

data <- list(mat1, mat2, mat3)

Thanks in advance!

timtams
  • 101
  • 6

1 Answers1

3

Make the list based on names (and it will be a named list this way)

data = mget(ls(pattern = "mat\\d+")) ## use a regex pattern to create a named list
data = lapply(data, as_tibble) ## convert the matrices to tibbles
names(data) = paste0(names(data), ".done") ## modify the names
list2env(data, envir = .GlobalEnv) ## put them back in global environment

Read more advice on this at How do I make a list of data frames?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Ok the names of the dataframes are more difficult, like "Data_Date01.31.22Time11.43.46.xlsx". And I let them read in automatically via folder name. So they're not really named in R itself. How does the first line look like then and how can I bring the names in R as well if necessary? – timtams Mar 10 '22 at 15:36
  • Depends how specific you need to be. `pattern = "^Data_Date.*"` will work if you want all objects that start with the pattern "Data_Date". `pattern = "xlsx$"` will give everything ending in "xlsx". Or `pattern = "^Data_Date.*xlsx$` is more specific, requiring that they start with "Data_Date" and end in "xlsx". You can find a intro to regex to understand what's going on there and learn about the possibilities. – Gregor Thomas Mar 10 '22 at 15:40
  • If I write your pattern in comment and ```names(data) <- paste0(files, ".done")``` it works. files it's the files I read in from a folder. – timtams Mar 10 '22 at 17:57