[R] Expanding a data structure

William Dunlap wdunlap at tibco.com
Mon Mar 1 04:06:54 CET 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Worik R
> Sent: Sunday, February 28, 2010 5:22 PM
> To: r-help
> Subject: [R] Expanding a data structure
> 
> I have a xts object with logical data .
> 
> > tail(q1)
>              ..1
> 2010-02-19  TRUE
> 2010-02-22 FALSE
> 2010-02-23 FALSE
> 2010-02-24 FALSE
> 2010-02-25 FALSE
> 2010-02-26 FALSE
> >
> 
> I want to build a xts that records the dates that there is a 
> change.  If
> TRUE -> FALSE it is "down" if FALSE -> TRUE it is "up"

   change <- c(NA, diff(q1$..1))
will be 1 when ..1 goes from FALSE
to TRUE, -1 for TRUE to FALSE, 0 for no change, and NA
for the first element.  You may find it convenient to
change that NA to something else or to not deal with
the first element after computing the diff.

You can map the -1,0,1 of diff() to your "down","up"
or "SELL","BUY" with ifelse() or subscripting, as in
   ifelse(change>0, "up", ifelse(change<0, "down","no change"))
or
   c("down","no change","up")[change+2]
and extract the dates of the ups with
   index(q1)[change==1]

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> 
> I can do it like this...
> 
> q2 <- matrix(ncol=2, nrow = length(q1[,1]))
> for(i in 1:length(q1)){
>   if(q1[i-1,1]){
>     ## Last one was TRUE
>     if(!q1[i, 1]){
>       ## Changed to FALSE
>       q2[j,] = c(as.character(index(q1[i,1])), "SELL")
>       j <- j+1
>     }
>   }else{
>     ## Last one was FALSE
>     if(q1[i, 1]){
>       ## Changed to TRUE
>       q2[j,] = c(as.character(index(q1[i,1])), "BUY")
>       j <- j+1
>     }
>   }
> }
>  q3 <- xts(q2[1:(j-1), 2], order.by=as.Date(q2[1:(j-1), 1]))
> 
> q3 is now the xts I want.  But there *has* to be a better way!
> 
> can anybody help?
> 
> cheers
> Worik
> 
> 
> What is wrong:
> * I am building a huge matrix then only using a few rows.  I need a
> structure I can dynamically add rows to.
> * q1[,1] is already a date.  Converting it to a string then 
> back to a date
> is superfluous, surly?
> 
> 	[[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.
> 



More information about the R-help mailing list