[R-SIG-Finance] Iterating through subset of XTS object
Joshua Ulrich
josh.m.ulrich at gmail.com
Tue Jul 5 15:30:38 CEST 2011
On Tue, Jul 5, 2011 at 12:53 AM, Noah Silverman <noahsilverman at ucla.edu> wrote:
> Hi,
>
> I have an xts object with 1 minute bars of trading data.
>
> I want to select a subset, then iterate through each bar. The "obvious" solution doesn't work:
>
> For each bar in the loop, I want to access all the fields (open, close, volume, etc.)
>
>
> I tried the following, but it doesn't work:
>
> ----------------------------------------------
> for( one in bars['T10:00/T10"30', ]){
> print(one$open)
> print(one$close)
> }
> ---------------------------------------------
>
A reproducible example would have been nice (a "bars" object and code
without syntax errors).
You're going to have this issue with a lot of objects and for loops
because ?"for" says that seq (the part of a for loop after in) is
"[A]n expression evaluating to a vector (including a list and an
expression) or to a pairlist or 'NULL'". xts objects are not strictly
vectors.
> is.vector(bars['T10:00/T10:30',])
[1] FALSE
So it gets coerced to numeric.
> as.numeric(bars['T10:00/T10:30',])
[1] 3 4 5 6 8 7 6 5
> Note: I DO need the loop for the code I'm writing.
>
> Can someone suggest the proper way to do this?
>
The proper way is to loop over the indices of the object.
for(i in 1:NROW(bars['T10:00/T10:30',])) {
bar <- bars[i,]
# do stuff
}
> Thanks!
>
> --
> Noah Silverman
> UCLA Department of Statistics
> 8117 Math Sciences Building
> Los Angeles, CA 90095
>
Best,
--
Joshua Ulrich | FOSS Trading: www.fosstrading.com
More information about the R-SIG-Finance
mailing list