【问题标题】:subtract a different vector from each row in a matrix in r从 r 中矩阵的每一行中减去一个不同的向量
【发布时间】:2019-11-29 05:08:36
【问题描述】:

我正在使用 R。 这些是我的数据:

  • Prot_before:一个有 70000 行的矩阵,每行有两列: 组(有 700 组)和每个样本的值(有 120 样本)。

  • Prot_healthy:一个有 30000 行的矩阵,每行有两列: 组(有 700 组)和每个样本的值(有 45 样本)。

对于prot_before 中的每一行,我想找到它的值减去prot_healthy 中该组中所有样本的值。

例如:

set.seed(100) 
Prot_before <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))             
Prot_before <- df[order(df$cat, df$val), ]  
Prot_before  
set.seed(100) 
Prot_after <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))             
Prot_after <- df[order(df$cat, df$val), ]  
Prot_after

现在我想要 prot_before 中每一行的结果,减去 prot_after 中同一组 aaa 等中的所有样本。所以对于prot_before 中的每一行,我得到 45 个结果。 我尝试使用扫描,但不知道如何按组对所有样本重复该功能。

如果写的不正确,我很抱歉,我不是很有经验。 谢谢!

【问题讨论】:

  • 你能提供预期的结果吗?

标签: r


【解决方案1】:

一种选择是将每个数据集的split 'cat' 转换为list,然后使用outer 对使用list 的相应list 元素的所有组合行进行减法@

Map(outer, MoreArgs = list(FUN = `-`), 
    split(Prot_before$val, Prot_before$cat), split(Prot_after$val, Prot_after$cat))

或者sapplyMap

Map(function(x, y) sapply(x, `-`, y),  
   split(Prot_before$val, Prot_before$cat), split(Prot_after$val, Prot_after$cat))

【讨论】:

    【解决方案2】:

    我们可以逐行使用apply,从Prot_after 中子集cat 并减去所有对应的val

    apply(Prot_before, 1, function(x) {
       as.numeric(x["val"]) - Prot_after$val[Prot_after$cat == x["cat"]]
    })
    

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 2014-08-22
      • 2015-05-15
      • 2011-07-17
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多