[R] applying a function in list of indexed elements of a vector:

R. Michael Weylandt michael.weylandt at gmail.com
Sun Mar 11 01:10:09 CET 2012


Your code for iy doesn't work as provided....I'll assume you meant this instead:

iy <- list(c(1, 2),c(1, 2), c(1, 2, 3, 4), c(2, 3, 5), c(4), c(5, 6,
7), c(7, 8, 9))

Then

sapply(iy, function(x) sum(Y1[x]))

Michael

On Sat, Mar 10, 2012 at 5:01 PM, aldi <aldi at dsgmail.wustl.edu> wrote:
> Hi,
>
> I have a vector
> Y1 <-c(8, 11,  7,  5,  6,  3,  6, 3,  3)
> and an index
> iy <-c(c(1, 2),c(1 2), c(1, 2, 3, 4), c(2, 3, 5), c(4), c(5, 6, 7), c(7, 8,
> 9))
>
> how can I produce the mean, or the sum of the elements specified in the
> index iy from the vector Y1?
>
> expecting something like this for the sum:
> Y2
> 19 19 31 24 5 15 12
>
> I thought lapply function may perform this, but does not work:
> Y2<-lapply(Y1[iy],sum)
>
> Any suggestion?
> TIA,
>
> Aldi
>
> --
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list