匹配行,在R中按组创建排名和总和

时间:2017-09-28 13:36:16

标签: r dataframe

我有一个包含~30,000行和~17,000列的庞大数据集,以及character元素的向量。

这是一个重新创建我的数据集的虚拟集

### Example

df <- data.frame(Gene=paste0("gene", 1:60), replicate(60, runif(60, min=0, max=100)))
colnames(df) <- c("GeneName", paste0("TisA.", 1:20), paste0("TisB.", 1:20), paste0("TisC.", 1:20))

genes <- sample(df$GeneName, 5)

head(df)
#      GeneName    TisA.1    TisA.2    TisA.3   TisA.4
#1    gene1  1.987621 17.936562 18.145417 59.43023
#2    gene2 60.031713 73.822846 93.946769 72.27633
#3    gene3 44.833748 47.890719 77.100497 39.45719
#4    gene4 44.662776 26.285659 30.087606 49.50682
#5    gene5 63.770411  6.469006  3.797708 68.17532

我需要匹配数据帧的向量中的元素,这可以通过

轻松完成
 df.new <- df[df$GeneName %in% genes,]

然后,我想要的是,genes中的每一个,为每个基因创建等级值,然后将等级加Tis(A,B,C)

我可以使用例如一个gene

来排序值
genes.ord <- sort(df.new[1,], decreasing = TRUE)

但是,我被困在这里,这将是为基因分配排名并按组排列这些排名的最快方法,即TisATisBTisC

为澄清起见,每组有20个样本TisA.1, TisA.2, ..., TisA.20

所需的输出是:

 GeneName   TisA TisB TisC
    gene4     24   32   10 ## these are random values to show sum of ranks for each of genes in the vector
    gene1     14   12   20 ## these are random values to show sum of ranks for each of genes in the vector
   gene40      4   92   12 ## these are random values to show sum of ranks for each of genes in the vector
    gene2     64    2   40 ## these are random values to show sum of ranks for each of genes in the vector
   gene15     84   32    9 ## these are random values to show sum of ranks for each of genes in the vector

P.S我的真实数据集中的一些值可以是0并在不同的列中重复

1 个答案:

答案 0 :(得分:1)

直接使用tidyverse

df1 <- apply(df[-1], 1, rank, ties.method= "first")
df2 <- apply(df1, 2, function(x){
  aggregate(x, list(sapply(strsplit(colnames(df), "[.]"), "[", 1)[-1]), sum)
  })
df3 <- cbind.data.frame(df$GeneName, t(Reduce(cbind, lapply(df2, "[", 2))))
colnames(df3) <- c("GeneName",  "TisA", "TisB", "TisC")
head(df3[order(df3$GeneName),])
GeneName TisA TisB TisC
   gene1  698  620  512
  gene10  525  653  652
  gene11  631  598  601
  gene12  487  679  664
  gene13  688  579  563
  gene14  674  581  575

或尝试使用baseR解决方案......有点复杂

{{1}}