R:将readRDS应用于.Rds文件名的列表对象 [英] R: Applying readRDS to a list object of .Rds file names

查看:215
本文介绍了R:将readRDS应用于.Rds文件名的列表对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个包含数据框架对象的.Rds文件,我想对每个文件应用一个函数,并将数据框架绑定到单个数据框架中.但是,当我尝试从文件名列表中读取多个.Rds文件时,收到错误消息:

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:

FUN(X [[i]],...)中的错误:从连接读取错误

Error in FUN(X[[i]], ...) : error reading from connection

readRDS不能与列表一起使用吗?

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)

推荐答案

purrr包中,函数map_df可以满足您的要求. map_df通过对各个元素进行行绑定来返回单个数据帧.

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.

这篇关于R:将readRDS应用于.Rds文件名的列表对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆