[R] apply (or similar preferred) for multiple columns
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Jul 12 23:07:27 CEST 2011
On Tue, Jul 12, 2011 at 5:27 AM, Dimitris.Kapetanakis
<dimitrios.kapetanakis at gmail.com> wrote:
> Dear all,
>
> I would like to use the apply or a similar function belonging to this
> family, but applying for each column (or row) but let say for each q
> columns. For example I would like to apply a function FUN for the first q
> columns of matrix X then for q+1:2*q and so on. If I do apply (X, 2, FUN) it
> applies for each column and not for every q columns. Is that possible with
> any similar function?
>
> Thank you
>
> Dimitris
Here is an example of using rollapply to sum all elements in the first
4 columns, then the next 4 columns, etc. anscombe is a data set that
comes with R. Be sure you are using zoo 1.7-0 which was just released
today.
> library(zoo)
> packageVersion("zoo")
[1] '1.7.0'
> rollapply(t(anscombe), 4, by = 4, sum, by.column = FALSE)
[1] 396.00 330.03
> c(sum(anscombe[, 1:4]), sum(anscombe[, 5:8]))
[1] 396.00 330.03
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list