【问题标题】:R reshape a matrix and join columnsR重塑矩阵并连接列
【发布时间】:2014-07-11 19:16:55
【问题描述】:

在提问之前,我尝试使用 cast、dcast,但一切都出错了......无论如何,我有一个这样的 data.frame

Genes                                               Code
 Apod Tptm      cell attachment cell to cell contact cell polarity
 Apod Serpine1  cell attachment cell to cell contact cell polarity
 Adm Ramp2                                        angiogenesis
 Adm Rdr                                          angiogenesis

我的想法是使用 Code 列重塑 data.frame 以在每种情况下将唯一代码作为行和唯一基因(避免重复)联合起来

Code                                                  Genes
cell attachment cell to cell contact cell polarity    Apod TpTm Serpine1
angiogenesis                                          Adm Rpr Ramp2

有什么想法吗?

谢谢

【问题讨论】:

  • 如果您将示例作为易于重现的块'o'代码提供,社区会喜欢它。请参阅stackoverflow.com/questions/5963269/… 了解如何处理。
  • 这实际上是“聚合”。您应该考虑使用您最喜欢的聚合方法的函数是 strsplitpaste
  • 好的,好的,关键是要获得独特的基因 unique(unlist(strsplit(c(DF[DF$Code=="ANGIOGENEIS","Genes"]),""))),我的问题是如何将重塑与此结合起来

标签: r dataframe reshape


【解决方案1】:

我认为这在基础 R 中也可以做到。

#sample data
test <- data.frame(Genes = c("Apod Tptm", "Apod Serpine1", "Adm Ramp2", "Adm Rdr"),
                   Code = c("X", "X", "Y", "Y"))

> test
#          Genes Code
#1     Apod Tptm    X
#2 Apod Serpine1    X
#3     Adm Ramp2    Y
#4       Adm Rdr    Y


test <- aggregate(Genes ~ Code, data=test, function(x) 
          paste(unique(unlist(strsplit(paste(x, sep=" "), " "))), collapse =" "))  

#result
> test
#  Code              Genes
#1    X Apod Tptm Serpine1
#2    Y      Adm Ramp2 Rdr

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2021-10-05
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多