我已经使用
Rdata
包中的 getMasterIndex
功能下载了一些 edgar
文件。
现在我尝试使用以下代码将所有这些文件加载到 RStudio 中 -
paths <- list.files('Master Indexes', pattern = '[.]Rda$', full.names = TRUE)
files <- map (paths, load)
list_rbind(files)
files
数据集的输出是,但是里面应该有数据。
[[1]]
[1] "year.master"
[[2]]
[1] "year.master"
[[3]]
[1] "year.master"
代码
list_rbind(files)
的输出是-
Error in `list_rbind()`:
! Each element of `x` must be either a data frame or `NULL`.
ℹ Elements 1, 2, and 3 are not.
Run `rlang::last_trace()` to see where the error occurred.
但是,最后一个
Rda
文件加载到 RStudio
中,名称为 year.master
我也使用了
for loop
功能,但结果还是一样。
我试图从此页面获取帮助,但它不起作用 - 使用 purrr 加载多个 rda 文件
我的目标是将所有 Rda 文件放入一个列表中,然后将其转换为数据框。
好吧,首先:清理您的环境(或保存您的环境,然后开始一个新的环境)。如果您像我一样,那么您那里有很多东西,因此很难看到加载的内容。
然后运行此代码:
pacman::p_load(edgar, tidyverse)
useragent <- "Your Name [email protected]"
getMasterIndex(2006, useragent)
getMasterIndex(2022, useragent)
rda_files <- dir("Master Indexes/", full.names = TRUE) |> grep(pattern = "\\.Rda", value = TRUE)
example <- load(rda_files[1])
files <- map(rda_files, ~ load(.x, .GlobalEnv))
所以你可以看到,尽管(看起来)你试图将文件加载为 对象
files
,它们实际上并没有保存在那里,而是以另一个名称“year.master”保存,并且函数返回该名称。看来 R 对象已加载其(可能是原始)名称。
来自文档:
替换当前环境(通常是您的工作区,.GlobalEnv)中具有相同名称的所有现有对象,因此可能会覆盖重要数据。使用load(<file>)
加载到不同的环境中,或者使用envir =
load() 到搜索路径中的新条目中,要安全得多。attach(file)
换句话说,因为它们都具有相同的名称,所以运行
map(rda_files, ~ load(.x, .GlobalEnv))
将加载所有它们,但您只会获得最后一个,因为每个都将覆盖之前的那个。