everyone! I have a very straight problem. I have a three dimensional array called w, like this:
每个人!我有一个很直接的问题。我有一个叫做w的三维数组,像这样
> 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).
我把第三维的元素加起来,比如w[1,1,1] + w[1, 1, 2] + w[1, 1, 3],但我不知道第三维会有多少个元素。我不能在for循环中这样做,因为它已经在一个嵌套的for循环中(两个for循环)。
So, I basically have to add together w[, , 1] + w[, , 2] + w[, , 3]....
所以,我基本上加一起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.
但它只打印w[,, 1],就是这样。
In c++, I think you would simply write y += w[, , n].
在c++中,我认为你只需写出y += w[, n]。
I would really appreciate some thoughts on how I should approach this or maybe a solution :).
我真的很想知道我该如何解决这个问题,或者也许是一个解决方案:)。
*edit: a very embarrassing typo.
编辑:一个非常尴尬的错误。
1 个解决方案
#1
2
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!
希望这可以帮助!
#1
2
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!
希望这可以帮助!