Re: [R] vectorize subscript ranges?

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Tue, 15 Jun 2010 01:35:19 -0400

On Jun 15, 2010, at 1:12 AM, James McCreight wrote:

> Hi R'ers-
>
> I'll believe this can be done and that I'm just not clever enough.
>
> I'm trying to do this in 2D, but i think we have the same problem in
> 1D.
>
> #Assume you have some 1D time series
> d<-rnorm(100)
>
> #Say you want to get the average over intervals of different lengths
> #like from time 10 to time 24 and time 51 to time 86
> starts <- c(10,51)
> ends <- c(24,86)
> results <-c(NA,NA)
>
> #then you'd typically loop
> for (i in 1:2) { results[i] <- mean(d[starts[i]:ends[i]) }
>
> can it be done without looping?

Depends on what you mean by "without looping":

 > mapply(function(x,y,z){mean(z[x:y])} ,x=starts, y=ends, MoreArgs=list(d))
[1] -0.219429514 -0.008565724

Probably no more, and quite possibly less, efficient than a for-loop.

>
> Thanks in advance.
>
> James
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.



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. Received on Tue 15 Jun 2010 - 05:37:50 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 15 Jun 2010 - 07:50:31 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive