简体   繁体   中英

Add together n-dimensions in a three dimensional array in R

everyone! I have a very straight problem. I have a three dimensional array called w , like this:

> 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 is just a representation , so this is not the actual data.

The thing is that I have add together the elements from the third dimensions, like 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 it in a for loop because it is within a nested for loop already (two for loops).

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

I tried something like

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

but it only prints the w[, , 1] and that is it.

In c++, I think you would simply write y += w[, , n].

I would really appreciate some thoughts on how I should approach this or maybe a solution :).

*edit: a very embarrassing typo.

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!

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