拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何使用R环境中的data.frames制作功能串列?

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

白鹭 - 2022-01-24 1965 0 0

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

多种方法可以合并多个资料集,由于我使用的是这种方法,因此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")

由于我想合并它们,我需要为它们添加相同的列。使用第一行代码,我列出了我在环境中拥有的变量(我只想要以名称“file”开头的 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 个时......这将是艰难的。为此,我想另辟蹊径。

我看到了这篇文章,我试过了,但它们没有保存为 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"

有谁知道该怎么做?

首先十分感谢

uj5u.com热心网友回复:

如果我们要合并的全域环境中有多个 data.frame,我们可以使用mgetand ls

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
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *