【发布时间】:2021-04-11 22:05:17
【问题描述】:
如何在 R 中处理两个具有多个数据帧的列表?示例数据:
set.seed(1)
set1 <- data.frame(NAME = paste("row_", 1:10, sep = ""),
SYMBOL = paste(c(sample(LETTERS, 10))),
SIGNIFICANT = sample(c("yes", "no"), 10, replace = TRUE))
set2 <- data.frame(NAME = paste("row_", 1:10, sep = ""),
SYMBOL = paste(c(sample(LETTERS, 10))),
SIGNIFICANT = sample(c("yes", "no"), 10, replace = TRUE))
set3 <- data.frame(NAME = paste("row_", 1:10, sep = ""),
SYMBOL = paste(c(sample(LETTERS, 10))),
SIGNIFICANT = sample(c("yes", "no"), 10, replace = TRUE))
set4 <- data.frame(NAME = paste("row_", 1:10, sep = ""),
SYMBOL = paste(c(sample(LETTERS, 10))),
SIGNIFICANT = sample(c("yes", "no"), 10, replace = TRUE))
files <- list(set1, set2, set3, set4)
names(files) <- paste("Set", 1:4, sep = "")
reports <- list(data.frame(SETS = c("Set1", "Set3"),
STATISTIC = runif(2)),
data.frame(SETS = c("Set2", "Set4"),
STATISTIC = runif(2)))
names(reports) <- c("Report1", "Report2")
files 是一个列表,其中包含来自分析的许多元数据数据帧。
> files$Set1
NAME SYMBOL SIGNIFICANT
1 row_1 Y no
2 row_2 D no
3 row_3 G no
4 row_4 A yes
5 row_5 B yes
6 row_6 K yes
7 row_7 N yes
8 row_8 R yes
9 row_9 W yes
10 row_10 J yes
reports 也是一个包含 2 个数据帧的列表,其中包含来自双向分析和相关统计数据的主要输出。
> reports$Report1
SETS STATISTIC
1 Set1 0.4100841
2 Set3 0.8108702
请注意,files 列表中数据框的名称与reports 列表中数据框的第 2 列相对应。
我希望以特定方式折叠这些files 元数据。如果files$Set1$SIGNIFICANT == 'yes',我想将相应的SYMBOL 附加到逗号分隔的字符串中。然后,我想将该字符串附加到reports 内的相应集合中。因此,我想要的输出如下:
> head(reports$Report1)
SETS STATISTIC SYMBOL
1 Set1 0.4100841 A, V, K, N, R, W, J
2 Set3 0.8108702 F, S, J, V
同样适用于Report2
对于这个例子来说手动操作很容易,但在我的实际项目中,length(files)=600
我正在尝试通过 for 循环解析它,但一直遇到错误。这是我当前的迭代
output <- data.frame()
for(i in 1:length(files)){
for(j in 1:nrow(files[[i]])){
if(files[j, 3] == "Yes"){
output[i, 1]=i;
output[i, 2]=paste0(i[,2], collapse = ", ")
}
}
}
还有我当前的错误:
Error in i[[j, 3]] : incorrect number of subscripts
我已经使用 R 大约 4 年了,如果我知道一件事,那就是人们经常避免像瘟疫这样的循环。我知道apply、lapply 等的一些变化可能会让生活变得轻松。
【问题讨论】: