简体   繁体   中英

Row wise matrix operations in R

Recently I ran into the data.table package. 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) ?

fun should take a vector as argument, for example mean , median , or 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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM