r - partial row-sums in multidimensional arrays -
i have question on how apply r functions multidimensional arrays.
for example, consider operation, reduce entry 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 case subtracting individual values might feasible, prefer vector-oriented approach.
if familiar multidimensional matrix algebra come matrix performs necessary operation when applied, complex given number of dimensions involved.
sum(ppl["2012",,,,,2:8]) not correct solution, sum() returns scalars.
i use loops perform necessary operations, contradicts paradigm of vector-oriented programming.
thanks help!
edit: , here solution 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 example of using apply , sum return sum computed across multi-dimensional table:
mat <- array(1:27, dim=c(3, 3, 3)) let's you'd compute sum of third dimension each combination of first 2 dimension.
then code becomes:
apply(mat, c(1,2), sum) [,1] [,2] [,3] [1,] 30 39 48 [2,] 33 42 51 [3,] 36 45 54
Comments
Post a Comment