Get the most out of xts object using merge function

Hi I am using the R quantize library and I would like to find and return at most two values ​​(volume today, vs volume yesterday).

require(quantmod)
getSymbols("HELE")
# Ok now when I do this it does not return a single column with the highest 
# volume 
head(    merge( HELE, max (HELE$HELE.Volume,lag(HELE$HELE.Volume, k=1    )  ) ) )

      

this usually works because, for example, I want to subtract yesterday from yesterday today, I can do that.

head(    merge(HELE, abs(HELE$HELE.High - lag(HELE$HELE.Close, k=1)   ) ) )

      

I also tried to apply the function but didn't work,

head(    merge(HELE, as.xts(apply( c(lag(HELE$HELE.Volume, k=1    ), HELE$HELE.Volume    ), 1, max) )      ) )

      

Thanks in advance. Ahdee

+3


source to share


1 answer


Try the following:

head(merge(HELE, pmax (HELE$HELE.Volume,lag(HELE$HELE.Volume, k=1), na.rm=TRUE)))

      

pmax

is a vectorized version max

, i.e. it finds pairwise max

between two vectors. You also need to enable na.rm=TRUE

, otherwise you will get NA where you are missing values.



Using only max

, it will find the global maximum between the two vectors and only create a column filled with that value.

Output:

> head(merge( HELE, pmax (HELE$HELE.Volume,lag(HELE$HELE.Volume, k=1 )  , na.rm=T) ) )
           HELE.Open HELE.High HELE.Low HELE.Close HELE.Volume HELE.Adjusted HELE.Volume.1
2007-01-03     24.25     25.16    24.25      25.12      251800         25.12        251800
2007-01-04     25.15     25.50    25.06      25.49      224400         25.49        251800
2007-01-05     25.45     25.50    24.78      24.93      289700         24.93        289700
2007-01-08     24.82     25.19    24.65      24.69      285000         24.69        289700
2007-01-09     21.84     22.60    21.75      22.19     1534800         22.19       1534800
2007-01-10     22.11     22.50    21.87      22.45      293600         22.45       1534800

      

+3


source







All Articles