基本上,我有一个数据帧,df
Beginning1 Protein2 Protein3 Protein4 Biomarker1
Pathway3 A G NA NA F
Pathway8 Z G NA NA E
Pathway9 A G Z H F
Pathway6 Y G Z H E
Pathway2 A G D NA F
Pathway5 Q G D NA E
Pathway1 A D K NA F
Pathway7 A B C D F
Pathway4 V B C D E
我想组合数据框,以便那些从“Protein2”到“Protein4”相同的行被浓缩,给出以下内容:
Beginning1 Protein2 Protein3 Protein4 Biomarker1
Pathway3 A,Z G NA NA F,E
Pathway9 A,Y G Z H F,E
Pathway2 A,Q G D NA F,E
Pathway1 A D K NA F
Pathway7 A,V B C D F,E
这与我之前提出的问题(Consolidating duplicate rows in a dataframe)非常相似,但不同之处在于我也在整合“Beginning1”行。
到目前为止,我已经尝试过:
library(dat.table)
dat<-data.table(df)
Total_collapse <- dat[, .(
Biomarker1 = paste0(Biomarker1, collapse = ", ")),
by = .(Beginning1, Protein1, Protein2, Protein3)]
Total_collapse <- dat[, .(
Beginning1 = paste0(Beginning1, collapse = ", ")),
by = .(Protein1, Protein2, Protein3)]
给出输出:
Beginning1 Protein2 Protein3 Protein4 Biomarker1
Pathway3 G NA NA F,E
Pathway9 G Z H F,E
Pathway2 G D NA F,E
Pathway1 D K NA F
Pathway7 B C D F,E
有谁知道如何解决这个问题?我也试过从Collapse / concatenate / aggregate a column to a single comma separated string within each group复制解决方案,但没有成功。
如果这是一个简单的错误,我很抱歉 - 我对R来说很新。
答案 0 :(得分:2)
使用df1['fb rq id']
,您可以使用data.table
来引用.SD
参数中未指定的所有列。然后,我们可以使用by
与lapply
完成paste()
。
collapse
输出
library(data.table)
dt <- read.table(text = "Beginning1 Protein2 Protein3 Biomarker1
A G NA NA F
Z G NA NA E
A G Z H F
Y G Z H E
A G D NA F
Q G D NA E
A D K NA F
A B C D F
V B C D E",header = T)
dt <- data.table(dt)
dt[,lapply(.SD, function(col) paste(col, collapse=", ")),
by=.(Protein2, Protein3, Protein4)]
答案 1 :(得分:1)
以下是使用dplyr
df %>% group_by_at(vars(Protein2:Protein4)) %>%
summarize_all(paste, collapse=",")
答案 2 :(得分:1)
我们可以使用aggregate
base R
r1 <- aggregate(cbind(Beginning1, Biomarker1)~., replace(df,is.na(df), "NA"), FUN = toString)
r1
# Protein2 Protein3 Protein4 Beginning1 Biomarker1
#1 B C D A, V F, E
#2 G Z H A, Y F, E
#3 G D NA A, Q F, E
#4 D K NA A F
#5 G NA NA A, Z F, E
r1[r1=="NA"] <- NA