Add together n-dimension in 3D array in R

all! I have a very direct problem. I have a 3D array called w , for example:

> w
, , 1

     [,1] [,2] [,3]
[1,]  0.5  0.5  0.5
[2,]  0.5  0.5  0.5

, , 2

     [,1] [,2] [,3]
[1,]  0.1  0.1  1.0
[2,]  0.5  0.5  0.5

      

Now it's just a show so this is not actual data.

The thing is, I've added members from third dimensions, for example w[1, 1, 1] + w[1, 1, 2] + w[1, 1, 3]

, but I don't know how many members the third dimension will have. I cannot do this in a for loop because it is already inside a nested loop (two for loops).

So, I basically have to add together w[, , 1] + w[, , 2] + w[, , 3]....

I have tried something like

for (k in 1:dims(w)[3]) # it is one of the for loops
lapply(w[, , k], '+') 

      

but it only prints w[, , 1]

and this is it.

In C ++, I think you would just write y + = w [, n].

I am very grateful for some thoughts on how I should approach this or maybe a solution :).

* edit: a very confusing typo.

+3


source to share


1 answer


It looks like this does what you want:

# sample data
w<-array(sample(1:4),dim=c(3,3,3))

# sum over dimensions 1 and 2
apply(w, MARGIN=c(1, 2), sum)

      



Hope this helps!

+2


source







All Articles