Convert all Environment files to '.Rda' and then load them at once with a loop

Asked

Viewed 119 times

2

I want to convert ALL dataframes of my Environment into file type .Rda. My goal is, after this action, to restart the R and load all of them at once with a loop for.

2 answers

3


Here’s a more automatic response if you have many data frames and don’t want to write each one’s name manually.

First part explaining how to save all Environment data frames:

# criar dados (apenas dois data frames no environment)
df1 <- data.frame(matrix(runif(12), nrow = 3))
df2 <- data.frame(matrix(runif(12), nrow = 3))
vec <- runif(12)
list <- list(runif(12), runif(12))

# obter os nomes dos data frames do environment
dflist <- names(Filter(is.data.frame, as.list(.GlobalEnv)))

# criar uma nova pasta para salvar os Rda's (showWarnings = FALSE para não mostrar os erros se a pasta já existir)
dir.create('dataframes', showWarnings = FALSE)

# salvar todos os data frames
for(i in dflist) {
  saveRDS(object = get(i), file = paste0('dataframes/', i, '.Rda'))
}

Now to read all automatically saved data frames:

# lista com os nomes dos data frames
dfNames <- dir('dataframes')

# retirar '.Rda'
objNames <- sub('\\.Rda$', '', dfNames) 

# ler os data frames
for(i in 1:length(dfNames)) {
  assign(objNames[i], readRDS(file = paste0('dataframes/', dfNames[i])))
}

1

Converts data.frames into list

df1 = data.frame(x=c(1:5))
df2 = data.frame(x=c(1:5), y=c(6:10))
df3 = data.frame(x=c(1:8), y=c(9:16), z=c(17:24))

lista_df = list(df1, df2, df3)

Saves the list in the list file_df.rds

saveRDS(lista_df, "lista_df.rds")

Load the list to the list file_df_new

lista_df_new = readRDS("lista_df.rds")

Converts the list to date.frames

for (i in 1:length(lista_df_new)){
  assign(paste("df",i, sep=""), value = data.frame(lista_df_new[[i]]) ) 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.