You can use rowSums() for this, using the "dims" argument to specify
that the first two dimensions are to be treated as row dimensions
(i.e. sum across the last dimension).
temp <- array(rnorm(3000*300*3), dim=c(3000,300,3))
> temp2 <- rowSums(temp, dims=2)
> dim(temp2)
[1] 3000 300
All of the functions
colMeans, colStdevs, colVars, colSums
rowMeans, rowStdevs, rowVars, rowSums
accept the dims argument in order to support arrays.
>Hi,
> I ran into an interesting question from one of our users. He had an array
>of about 3000 by 300 by 3. He tried to use apply to sum the last dimension:
>
>result <- apply(array, c(1,2), sum)
>
> I'm not sure he was ever able to get the result. He was surprised
>because he could use apply over different dimensions and had no problem:
>
>wrong.result <- apply(array, c(2,3), sum)
>
> I suggested that he simply break down the problem into a simple
>summation:
>
>result <- array[,,1] + array[,,2] + array[,,3]
>
> That executed very fast.
>
> My question is "Has anybody constructed a list of functions that do not
>scale well under certain circumstances?" I remember seeing something
>within the last year about outer being very slow for long vectors and
>clearly, there are some problems with apply.
Any solution that involves looping, either explicitly (for, while, repeat)
or hidden (apply, lapply, sapply...) has the potential to slow down
for long loops. The apply functions are generally better than
explicit loops.
outer() does not involve looping, unless the function being called does
looping internally. It should be fine, unless the sheer size of the
problem is large.
Tim Hesterberg
========================================================
| Tim Hesterberg Research Scientist |
| timh@insightful.com Insightful Corp. |
| (206)802-2319 1700 Westlake Ave. N, Suite 500 |
| (206)802-2500 (fax) Seattle, WA 98109-3044, U.S.A. |
| www.insightful.com/Hesterberg |
========================================================
Download the S+Resample library from www.insightful.com/downloads/libraries
|