R语言 按data.table中的行名合并

xwmevbvl  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(304)

我想使用this解决方案,两个合并两个数据。表的行名称。但它不工作。

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")))

tt <-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")))

z <- as.data.frame(z)
tt <- as.data.frame(tt)

setDT(z)
setDT(tt)

merge(tt,z["symbol"],by="row.names",all.x=TRUE)

我得到错误:

Error in `[.data.table`(z, "symbol") : 
  When i is a data.table (or character vector), the columns to join by must be specified using 'on=' argument (see ?data.table), by keying x (i.e. sorted, and, marked as sorted, see ?setkey), or by sharing column names between x and i (i.e., a natural join). Keyed joins might have further speed benefits on very large data due to x being sorted in RAM.

这在data.table中是如何工作的?

ffscu2ro

ffscu2ro1#

你可以用merge合并两个矩阵,合并后的集合将是一个data.frame,列名为“Row.names”。之后,你可以根据需要将它变成一个data.table。

merged <- merge(tt, z, by = "row.names", all = TRUE)

setDT(merged)

或者你可以决定先把矩阵转换成data.table,然后把dimnames作为一个新列添加进去,然后合并这两个data.table。

merge(
  as.data.table(z)[, id := dimnames(z)[[1]]],
  as.data.table(tt)[, id := dimnames(tt)[[1]]],
  all = T
)

相关问题