在R中,从矩阵的每一行中减去不同的向量

3
我使用R语言。 这是我的数据:
  • Prot_before: 一个70000行的矩阵,每行有两列: group(共有700个组)和每个样本的值(共有120个样本)。

  • Prot_healthy: 一个30000行的矩阵,每行有两列: group(共有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。所以对于 prot_before 中的每一行,我会得到45个结果。

我尝试使用sweep,但不知道如何按组重复执行该函数。

如果我的表达方式有误,很抱歉,我经验不足。

谢谢!


你能提供期望的结果吗? - Cole
2个回答

1

一种选项是将每个数据集按'cat' split成一个list,然后使用outer对相应的list元素的所有组合行进行减法运算,使用Map

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

1
我们可以逐行使用 apply,从 Prot_after 中子集出 cat 并减去所有相应的 val 值。
apply(Prot_before, 1, function(x) {
   as.numeric(x["val"]) - Prot_after$val[Prot_after$cat == x["cat"]]
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接