按行应用函数但在 R 中没有应用函数

apply a function by rows but without apply function in R

我正在尝试应用一个函数,该函数采用矩阵并将每个元素除以其行的总和。具体来说,我有矩阵

mat <- matrix(1:10, nrow = 2) 

然后我将函数 calculateContributions 应用到每一行,如下所示:

apply(mat, 1, calculateContributions) 

calculateContributions函数定义:

calculateContributions <- function(X){
  return(X/sum(X))
}

这给了我需要的结果,但是由于应用函数非常慢并且我需要多次计算,所以这个解决方案不是很好。我认为函数 with 可能会有所帮助,但我不知道如何使用它按行应用函数。

正如@DavidArenburg 建议的那样,

mat/rowSums(mat)

似乎是最简单的方法。使用 1e5 个元素进行测试;

mat <- matrix(sample(1:100,1e5,replace=TRUE), ncol = 5) 
dim(mat)
[1] 20000     5

library(microbenchmark)    
microbenchmark(a <- mat/rowSums(mat), unit="ms")
# Unit: milliseconds
# expr      min        lq      mean    median      uq      max neval
# *    0.767314 0.7937865 0.8235583 0.8070225 0.81532 2.461567   100

calculateContributions <- function(X){
  return(X/sum(X))
}

microbenchmark(b <- apply(mat, 1, calculateContributions), unit="ms")
# Unit: milliseconds
# expr      min       lq     mean   median       uq      max neval
# *    84.44795 86.19673 89.37455 87.41942 89.72254 164.3082   100

所以只做矩阵除法就快了 100 倍。

更糟糕的是,apply 调用的结果是转置矩阵(来源:@DavidArenburg),因此您仍然需要转换回来。当你这样做时,你会得到与矩阵除法完全相同的结果。

identical(a, t(b))
[1] TRUE

旁注:(我在这里还是新手)为什么人们将有效答案添加为评论(为什么我因为使用​​归因和额外细节做出这些答案而被否决?)。