danas.zuokas
danas.zuokas

Reputation: 4643

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.

Upvotes: 6

Views: 4176

Answers (1)

Christoph_J
Christoph_J

Reputation: 6884

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.

Upvotes: 4

Related Questions