[R] apply(ing) to sum subset of a vector

Jacques VESLOT jacques.veslot at cirad.fr
Mon Mar 27 11:45:25 CEST 2006


apply(cbind(from,to), 1, function(x) sum(g[x[1]:x[2]]))

Fred J. a écrit :

>Dear R users
> 
> I am trying to sum selective elements of a vector but my solution
> is not cutting it.
> 
> Example:
> > g <- 1:5;
> 
> > from <- 1:3;
> > to <- 3:5;
> from to
> 1       3
> 2       4
> 3       5
> 
> so I expect 3 sums from g
> 1+2+3  that is 1 to 3 of g
> 2+3+4  that is 2 to 4 of g
> 3+4+5  that is 3 to 5 of g
> 
> my solution will not work.
> sum.em <- function(g, c1, c2) sum(g[c1:c2])
> apply(g, 1, sum.em, ...) I don't think so because apply is not
> aware of the from and to. and if I f <- list(g, from, to) that will not fit with the second arg of apply.
> 
> thank you
> 
>			
>---------------------------------
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
>  
>




More information about the R-help mailing list