How to apply pmax to xts object in r?

I have an xts object of realized (stocks) volatility, and I want to impose a minimum volatility for each stock / column. Here is a sample that I cannot work correctly. It cyclically moves along the minimum wave vector. Thanks.

require(xts)
set.seed(3)    
A <- matrix(runif(18, max=0.30), ncol=3)
A.xts <- xts(A, Sys.Date()-6:1)
Min_Vols <- c(.10, .20, .30)
B <- pmax(as.matrix(A.xts), Min_Vols)
A.xts; B

The above creates

                 [,1]       [,2]       [,3]
2015-08-28 0.05041246 0.03739003 0.16021061
2015-08-29 0.24225492 0.08838028 0.16717483
2015-08-30 0.11548271 0.17328298 0.26037585
2015-08-31 0.09832030 0.18929378 0.24891261
2015-09-01 0.18063020 0.15360477 0.03343475
2015-09-02 0.18131822 0.15150717 0.21110651
                [,1]      [,2]      [,3]
2015-08-28 0.1000000 0.1000000 0.1602106
2015-08-29 0.2422549 0.2000000 0.2000000
2015-08-30 0.3000000 0.3000000 0.3000000
2015-08-31 0.1000000 0.1892938 0.2489126
2015-09-01 0.2000000 0.2000000 0.2000000
2015-09-02 0.3000000 0.3000000 0.3000000

Where I want to be B:

                 [,1]       [,2]       [,3]
2015-08-28 0.10000000 0.20000000 0.30000000
2015-08-29 0.24225492 0.20000000 0.30000000
2015-08-30 0.11548271 0.20000000 0.30000000
2015-08-31 0.10000000 0.20000000 0.30000000
2015-09-01 0.18063020 0.20000000 0.30000000
2015-09-02 0.18131822 0.20000000 0.30000000
+4
source share
2 answers

You can use sapplyto impose your column restrictions

B<-sapply(1:ncol(A),function(i) pmax(A[,i],Min_Vols[i]))
xts(B,index(A.xts))

#>                 [,1] [,2] [,3]
#> 2015-08-28 0.1000000  0.2  0.3
#> 2015-08-29 0.2422549  0.2  0.3
#> 2015-08-30 0.1154827  0.2  0.3
#> 2015-08-31 0.1000000  0.2  0.3
#> 2015-09-01 0.1806302  0.2  0.3
#> 2015-09-02 0.1813182  0.2  0.3
+2
source

You have a couple of options. You can create a matrix to go to pmax:

MinVolMatrix <- matrix(Min_Vols, nrow(A), ncol(A), byrow=TRUE)
B <- as.xts(pmax(as.matrix(A.xts), MinVolMatrix))

apply ( , - , apply ):

B <- as.xts(t(apply(A.xts, 1, pmax, Min_Vols)))
+1

Source: https://habr.com/ru/post/1605792/


All Articles