[R] Add a vector to the values in a specific dimension of an array

Ian Gow iandgow at gmail.com
Thu May 19 07:51:28 CEST 2011


Hi:

Reordering the dimensions, then doing a vectorized addition, then reordering (back) again is faster, it seems.

> m <- 20; n <- 30; p <- 40; q <- 30
>  a <- NA
> length(a) <- m * n * p * q
> dim(a) <- c(m, n, p, q)
> x <- 1:n
> a[1:m,,1:p,1:q] <- 0
> b <- a
> 
> # Approach 1
> system.time({
+ c <- aperm(a,c(2,1,3,4))
+ c <- c + x
+ a <- aperm(c,c(2,1,3,4))
+ })
   user  system elapsed 
  0.019   0.001   0.019 
> 
> # Approach 2
> system.time({
+ b[1:m,,1:p,1:q] <- 0
+ for (mm in 1:m) {
+  for (pp in 1:p) {
+    for (qq in 1:q) {
+      b[mm,,pp,qq] <- x
+    }
+  }
+ }
+ })
   user  system elapsed 
  0.149   0.002   0.150 
> all(b==a)
[1] TRUE
> 


On May 18, 2011, at 11:47 PM, huron wrote:

> Hello,
> 
> A simple question, although I can't find an answer via my google/forum
> search:
> 
> I have a 4-dimensional array; call it A[1:M,1:N,1:P,1:Q]. I have a vector x
> that is N by 1.  
> 
> I would like to "quickly" add x to the 2nd dimension of A; in other words, I
> want a quicker way of doing the following:
> 
> for (m in 1:M) {
>  for (p in 1:P) {
>    for (q in 1:Q) {
>      A[m,,p,q] = A[m,,p,q] + x
>    }
>  }
> }
> 
> Thanks in advance!
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/Add-a-vector-to-the-values-in-a-specific-dimension-of-an-array-tp3534730p3534730.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list