【问题标题】:How do I apply pmax to an xts object in r?如何将 pmax 应用于 r 中的 xts 对象?
【发布时间】:2015-11-29 15:07:15
【问题描述】:

我有一个已实现(股票)波动率的 xts 对象,我想为每个股票/列强加一个最小波动率。这是一个我无法正常工作的示例。它奇怪地循环通过最小 vol 向量。谢谢。

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

以上生成

                 [,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

我希望 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

【问题讨论】:

  • 使用并显示set.seed 来生成您的示例数据。显示预期输出。猜你想要sapply(1:ncol(A),function(i) pmax(A[,i],Min_Vols[i]))
  • 谢谢你,A. Webb,我做了如图所示的编辑。
  • 我的真实代码的行为与上面的示例不同,并在运行时生成以下错误:sapply(1:ncol(Vols.xts), function(i) pmax(Vols.xts[,i],Min_Vols[i])) whch 给出:Error in array(r, dim = d, dimnames = if (!(is.null(n1 &lt;- names(x[[1L]])) &amp; : length of 'dimnames' [1] not equal to array extent 最终要修复它,我必须使用 @ 转换 xts 对象987654328@ 然后将其转换回来。这是我遇到的问题。我看到@Joshua-Ulrich 在下面显示了这一点。我不知道为什么我们的示例代码中简单的 A B 版本不会出现此错误。

标签: r xts


【解决方案1】:

您可以使用sapply 对列施加约束

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】:

    您有几个选择。你可以创建一个矩阵来传递给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)))
    

    【讨论】:

    • 您可以使用B&lt;- matrix(pmax(Min_Vols, t(A)), byrow=TRUE, ncol=3)来简化并避免创建新矩阵
    猜你喜欢
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多