如何使用 R 环境中的 data.frames 制作功能列表?

How to make a functional list with the data.frames from the environment in R?

我想将几个 data.frames 合而为一。所有 data.frames 共享相同的列。

different ways 可以合并多个数据集,并且由于我正在使用这种方法 Reduce(function(...) merge(..., all=TRUE), list( )) 我需要获取我在环境中拥有的 data.frames 的列表。 但是,每次我尝试获取它们的列表时,作为 data.frame 的特征都会消失,它们仅保存为名称。

这些是我的数据框:

file_1 <- women
file_2 <- women
colnames(file_2) <- c("height_2", "weight_2")
file_3 <- women
colnames(file_3) <- c("height_3", "weight_3")
file_4 <- women
colnames(file_4) <- c("height_4", "weight_4")
file_5 <- women
colnames(file_5) <- c("height_5", "weight_5")

因为我想合并它们,所以我需要为它们添加相同的列。 在第一行代码中,我列出了我在环境中拥有的变量(我只想要以名称“文件”开头的 data.frames)

list_files <- grep("file",names(.GlobalEnv),value=TRUE)

for (file in list_files){
  temp <- get(file)
  # We add the column 
  temp$ID <- "col"
  #we return the change in the file
  assign(file, temp)
}
rm(temp) #we don't need it anymore.

但是,当我尝试使用 list_files(具有 data.frames 的名称)合并它们时,我没有得到正确的 data.frame 合并。

DF_complete <- Reduce(function(...) merge(..., all=TRUE), list(list_files))

> class(DF_complete)
[1] "character"

另一方面,当我尝试这段代码(我自己编写所有数据帧)时,我得到了我想要的数据帧。

DF_2 <- Reduce(function(...) merge(..., all=TRUE), list(file_1, file_2, file_3, file_4, file_5))

class(DF2)
[1] "data.frame"

我想避免写所有 data.frames。现在我有 5 个 data.frames,但是当我有超过 10 个时……这会很困难。为此,我想另辟蹊径。

我看到了这个 post 并且我试过了,但是它们没有保存为 data.frames。

list_df <- list(list_files)
> list_df
[[1]]
[1] "file_1" "file_2" "file_3" "file_4" "file_5"
class(list_df)
[1] "list"

有人知道怎么做吗?

非常感谢

如果我们要合并的全局环境中有多个data.frames,我们可以使用mgetls:

file_1 = data.frame(id = c(1,2), a = c(1,2))
file_2 = data.frame(id = c(1,2), b = c(3,4))
file_3 = data.frame(id = c(3,4), a = c(5,6))

Reduce(\(...) merge(..., all = T), mget(ls(pattern = "file")))
  id a  b
1  1 1  3
2  2 2  4
3  3 5 NA
4  4 6 NA