Re: [R] More effective calculation for loop

From: Joshua Ulrich <josh.m.ulrich_at_gmail.com>
Date: Fri, 13 May 2011 11:05:20 -0500

On Fri, May 13, 2011 at 4:32 AM, Wolfgang Wu <wobwu22_at_yahoo.de> wrote:
> I am getting confused in how to use R effectively. Below is the example that I
> would like to optimize, which is basically a loop. In its current version it
> takes  about 20 seconds to run. I have looked at the apply function and but
> didn't seem to get it to work. I am sure this is relatively easy to show me a
> better version for someone who has done this before. For some reason I seem to
> have trouble getting my head around this.
>
> #----------------------------------
> #Create the example data
> dDates <- seq(from=as.Date("1990-01-01"), by="day", length.out=10000);
> xtsHold <- xts(rep(0, times=10000), order.by=dDates);
> xtsBuy <- xts(sample(0:1,10000,replace=T), order.by=dDates);
> xtsSell <- xts(sample(0:1,10000,replace=T), order.by=dDates);
> print(Sys.time())
>
> #Run the inefficient calculation
> for (i in 2:length(xtsHold)){
> xtsHold[i] <- xtsHold[i-1] + xtsBuy[i-1] - xtsSell[i-1];
> }
>
> print(Sys.time())#----------------------------------
>
Use a vectorized solution instead:

xtsHold2 <- lag(xtsBuy)-lag(xtsSell)
xtsHold2[1] <- 0
xtsHold2 <- cumsum(xtsHold2)
identical(xtsHold, xtsHold2)

>
> Thank you very much in advance!
>
> Best regards,
>
> Wolfgang Wu
>
>
> ______________________________________________
> 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.
>

--
Joshua Ulrich  |  FOSS Trading: www.fosstrading.com

______________________________________________
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 Fri 13 May 2011 - 16:10:26 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

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 Fri 13 May 2011 - 16:20:07 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