Hi I'm using R quantmod library and I would like to find and return the maximum of 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 generally works because for example say I want to subtract today's high from yesterday close I can do this.
head( merge(HELE, abs(HELE$HELE.High - lag(HELE$HELE.Close, k=1) ) ) )
I also tried apply function but did not work as well,
head( merge(HELE, as.xts(apply( c(lag(HELE$HELE.Volume, k=1 ), HELE$HELE.Volume ), 1, max) ) ) )
Thanks in advance. Ahdee
Try this:
head(merge(HELE, pmax (HELE$HELE.Volume,lag(HELE$HELE.Volume, k=1), na.rm=TRUE)))
pmax
is the vectorised version of max
i.e. it finds the pairwise max
between two vectors. You also need to include a na.rm=TRUE
otherwise you will end up with NAs where you have missing values.
Using only max
it would find the global max between the two vectors and create a column filled with this value only.
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