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

Bill.Venables at csiro.au Bill.Venables at csiro.au
Thu May 19 08:26:23 CEST 2011


It depends on how big A is and how much memory you have.  Here is one lazy way.

A <- aperm(aperm(A, c(2,1,3,4)) + x, c(2,1,3,4))

Bill Venables

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of huron
Sent: Thursday, 19 May 2011 1:47 PM
To: r-help at r-project.org
Subject: [R] Add a vector to the values in a specific dimension of an array

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