按行名合并或组合
Posted
技术标签:
【中文标题】按行名合并或组合【英文标题】:Merge or combine by rownames 【发布时间】:2011-08-27 03:34:57 【问题描述】:在下面的示例中,我有两个数据集(Z 和 A)。我想通过 ILMN 编号合并或组合这些集合。如果没有匹配,填写NA。
z <- matrix(c(0,0,1,1,0,0,1,1,0,0,0,0,1,0,1,1,0,1,1,1,1,0,0,0,"RND1","WDR", "PLAC8","TYBSA","GRA","TAF"), nrow=6,
dimnames=list(c("ILMN_1651838","ILMN_1652371","ILMN_1652464","ILMN_1652952","ILMN_1653026","ILMN_1653103"),c("A","B","C","D","symbol")))
t<-matrix(c("GO:0002009", 8, 342, 1, 0.07, 0.679, 0, 0, 1, 0,
"GO:0030334", 6, 343, 1, 0.07, 0.065, 0, 0, 1, 0,
"GO:0015674", 7, 350, 1, 0.07, 0.065, 1, 0, 0, 0), nrow=10, dimnames= list(c("GO.ID","LEVEL","Annotated","Significant","Expected","resultFisher","ILMN_1652464","ILMN_1651838","ILMN_1711311","ILMN_1653026")))
结果会是这样的:
[,1] [,2] [,3] [,4]
GO.ID "GO:0002009" "GO:0030334" "GO:0015674" NA
LEVEL "8" "6" "7" NA
Annotated "342" "343" "350" NA
Significant "1" "1" "1" NA
Expected "0.07" "0.07" "0.07" NA
resultFisher "0.679" "0.065" "0.065" NA
ILMN_1652464 "0" "0" "1" PLAC8
ILMN_1651838 "0" "0" "0" RND1
ILMN_1711311 "1" "1" "0" NA
ILMN_1653026 "0" "0" "0" GRA
【问题讨论】:
【参考方案1】:您可以将 -Andrie 答案包装到一个通用函数中
mbind<-function(...)
Reduce( function(x,y)cbind(x,y[match(row.names(x),row.names(y)),]), list(...) )
这里可以绑定多个以rownames为key的frame
【讨论】:
【参考方案2】:cbind.fill <- function(x, y)
xrn <- rownames(x)
yrn <- rownames(y)
rn <- union(xrn, yrn)
xcn <- colnames(x)
ycn <- colnames(y)
if(is.null(xrn) | is.null(yrn) | is.null(xcn) | is.null(ycn))
stop("NULL rownames or colnames")
z <- matrix(NA, nrow=length(rn), ncol=length(xcn)+length(ycn))
rownames(z) <- rn
colnames(z) <- c(xcn, ycn)
idx <- match(rn, xrn)
z[!is.na(idx), 1:length(xcn)] <- x[na.omit(idx),]
idy <- match(rn, yrn)
z[!is.na(idy), length(xcn)+(1:length(ycn))] <- y[na.omit(idy),]
return(z)
【讨论】:
【参考方案3】:使用合并并将您的 t 向量重命名为 tt(参见 Andrie 的 PS):
merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]
现在,如果您使用数据帧而不是矩阵,这甚至会变得容易得多:
z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)
【讨论】:
【参考方案4】:使用match
返回你想要的向量,然后cbind
它到你的矩阵
cbind(t, z[, "symbol"][match(rownames(t), rownames(z))])
[,1] [,2] [,3] [,4]
GO.ID "GO:0002009" "GO:0030334" "GO:0015674" NA
LEVEL "8" "6" "7" NA
Annotated "342" "343" "350" NA
Significant "1" "1" "1" NA
Expected "0.07" "0.07" "0.07" NA
resultFisher "0.679" "0.065" "0.065" NA
ILMN_1652464 "0" "0" "1" "PLAC8"
ILMN_1651838 "0" "0" "0" "RND1"
ILMN_1711311 "1" "1" "0" NA
ILMN_1653026 "0" "0" "0" "GRA"
附言。 请注意 t
是用于转置矩阵的基本 R 函数。通过创建一个名为 t 的变量,可能会导致下游代码混乱。
【讨论】:
您的回答非常有用,谢谢。唯一的问题是我的代码没有给出正确的输出。如果我只接受这个: z[, "symbol"][match(rownames(t), rownames(z))] 使用 NA 和符号创建一个因子,但是当我执行 cbind 时,符号编号被替换为 rondom 值.有谁知道这是错的?谢谢 请更正您 PS 中的错误。您不会覆盖t
函数。您正在为用户制造混乱,但数据和功能存储在不同的位置。来吧,测试一下: t
【参考方案5】:
不完美但接近:
newcol<-sapply(rownames(t), function(rn)z[match(rn, rownames(z)), 5])
cbind(data.frame(t), newcol)
【讨论】:
以上是关于按行名合并或组合的主要内容,如果未能解决你的问题,请参考以下文章
如何在不添加“Row.names”列的情况下按行名合并数据框?