Reputation: 331
I have several .Rds files containing data frame objects and I want to apply a function to each file and bind the data frames into a single data frame. However, when I try to read in multiple .Rds file from a list of file names, I receive the error:
Error in FUN(X[[i]], ...) : error reading from connection
Does readRDS not work with lists?
########################
# Reproducible example
########################
library(dplyr)
# Create .Rds files
saveRDS(data.frame(a = seq(1:3), b = rep("a",3)),"a.Rds")
saveRDS(data.frame(a = seq(9:11), b = c("j","h","o")),"b.Rds")
# Create list of file names to read
rds <- list("a.Rds","b.Rds")
# Read in .Rds files (error occurs here)
temp <- lapply(rds, readRDS)
# Converts file to single data frame
final <- do.call(dplyr::bind_rows, temp)
Upvotes: 3
Views: 5016
Reputation: 584
In the purrr
package the function map_df
does what you want. map_df
returns a single dataframe by row-binding the individual elements.
saveRDS(data.frame(a = 1:3, b = rep("a",3)),"a.Rds")
saveRDS(data.frame(a =9:11, b = c("j","h","o")),"b.Rds")
# Create list of file names to read
rds <- c("a.Rds","b.Rds")
library(purrr)
purrr::map_df(rds, readRDS)
The edited version corrects a small error in the example.
Upvotes: 2