开发者

partial row-sums in multidimensional arrays

I have a question on how to apply R functions to multidimensional arrays.

For example, consider thi开发者_JAVA技巧s operation, where I reduce an entry by the sum of other entries.

ppl["2012",,,,,1] <- ppl["2012",,,,,1]
- ppl["2012",,,,,2] - ppl["2012",,,,,3] - ppl["2012",,,,,4]
- ppl["2012",,,,,5] - ppl["2012",,,,,6] - ppl["2012",,,,,7]
- ppl["2012",,,,,8]

While in this case subtracting individual values might be feasible, I would prefer a vector-oriented approach.

If I was familiar with multidimensional matrix algebra I could probably come up with the matrix that performs the necessary operation when applied, but this is too complex given the number of dimensions involved.

sum(ppl["2012",,,,,2:8]) is not the correct solution, as sum() always returns scalars.

I could use loops that perform the necessary operations, but that contradicts the paradigm of vector-oriented programming.

Thanks for your help!

Edit: And here is the solution to the original problem, based on Andrie's suggestion: ppl[paste(i),land,,,,1] <- ppl[paste(i),land,,,,1] - apply(ppl[paste(i),land,,,,2:8],c(1,2,3),sum)


EDITED

Here is an example of using apply and sum to return the sum computed across a multi-dimensional table:

mat <- array(1:27, dim=c(3, 3, 3))

Let's say you'd like to compute the sum of the third dimension for each combination of the first two dimension.

Then the code to do this becomes:

apply(mat, c(1,2), sum)

     [,1] [,2] [,3]
[1,]   30   39   48
[2,]   33   42   51
[3,]   36   45   54
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜