[英]Row wise matrix operations in R
Recently I ran into the data.table
package.最近我遇到了
data.table
包。 I'm still not sure how to do row-wise matrix operations.我仍然不确定如何进行逐行矩阵运算。 Was it originally intended to handle such operations?
它最初是为了处理此类操作吗? For example, what would be data.table equivalent to
apply(M,1,fun)
?例如,什么是 data.table 相当于
apply(M,1,fun)
?
fun
should take a vector as argument, for example mean
, median
, or mad
. fun
应该将向量作为参数,例如mean
、 median
或mad
。
I think you are looking for the :=
operator (see ?':='
).我认为您正在寻找
:=
运算符(请参阅?':='
)。 A short example and a comparison with the mapply
function is below (I hope I apply the mapply
function correctly; I'm only using data.tables nowadays, so no promise on that; but still, the data.table way is fast and in my opinion easy to memorize):下面是一个简短的示例和与
mapply
函数的比较(我希望我正确应用了mapply
函数;我现在只使用 data.tables,所以对此没有任何承诺;但是,data.table 的方式仍然很快而且很方便我的意见很容易记住):
library(data.table)
> df <- data.frame(ID = 1:1e6,
+ B = rnorm(1e6),
+ C = rnorm(1e6))
> system.time(x <- mapply(foo, df$B, df$C))
user system elapsed
4.32 0.04 4.38
> DT <- as.data.table(df)
> system.time(DT[, D := foo(B, C)])
user system elapsed
0.02 0.00 0.02
> all.equal(x, DT[, D])
[1] TRUE
After posting my answer, I'm not so sure anymore if this is what you are looking for.发布我的答案后,我不确定这是否是您正在寻找的。 I hope it does, just give more details if it doesn't (for instance, do you have many columns you want to apply a function to, not just the two in my example?).
我希望是这样,如果不是,请提供更多详细信息(例如,您是否有许多列要应用函数,而不仅仅是我的示例中的两个?)。 Anyways, this SO post could be of interest for you.
无论如何,这篇SO 帖子可能会让您感兴趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.