【问题标题】:How can I fill in a matrix with vector of different length如何用不同长度的向量填充矩阵
【发布时间】:2021-02-26 13:00:40
【问题描述】:

所以基本上我有 3 个看起来像这样的向量

观察日期(1、2、3、1、2) 产量 (0.05, 0.06, 0.01, 0.02, 0.04) 到期日 (3, 3, 4, 5, 3)

每个产量都与特定的观察日期相关联。以第一个收益率为例,在第 1 天,收益率为 0.05 的债券还有 3 年到期。

我正在尝试创建一个矩阵,其中包含观察日期的行和成熟度长度的列;然后用产量填充矩阵。对我来说,困难的部分是弄清楚如何将收益率放在正确的位置,因为在某些观察日期或期限长度上,收益率可能不存在。我想知道是否有一种机制可以帮助我参考观察日期和成熟度并直接为我找到收益。 任何想法将不胜感激!

【问题讨论】:

    标签: r matrix finance


    【解决方案1】:

    1.一般方法:您可以在基础 R 中创建一个矩阵:

    ## vectors with same length
    
    obs_date <- c(1,2,3,1,2)
    yields <- c(0.05,0.06,0.01,0.02,0.04)
    maturities <- c(3,3,4,5,3)
    
    # creating matrix 
    m <- matrix(c(obs_date, yields, maturities), ncol = 3) 
    
    # print matrix 
    print(m) 
    
    # print class of m 
    class(m) 
    

    2。如何创建具有不同长度向量的矩阵:

    ## vectors of different length
    
    obs_date_1 <- c(1,2,3,1)
    yields_1 <- c(0.05,0.06,0.01,0.02,0.04)
    maturities_1 <- c(3,3,4)
    
    # create a list of vectors
    listofvectors <- list(obs_date_1, yields_1, maturities_1)
    
    # create the matrix
    matrixofdiffvec_length <- sapply(listofvectors, '[', seq(max(sapply(listofvectors, length))))
    
    matrixofdiffvec_length
    
    class(matrixofdiffvec_length)
    

    【讨论】:

      【解决方案2】:

      试试下面的代码段。你需要在你的机器上安装 tidyverse 包。

      obs_date <- c(1,2,3,1,2)
      yields <- c(0.05,0.06,0.01,0.02,0.04)
      maturities <- c(3,3,4,5,3)
      library(tidyverse)
      mat <- tibble(obs_date, yields, maturities)
      mat
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-21
        • 2021-04-30
        • 2021-11-03
        • 2014-11-19
        • 1970-01-01
        • 1970-01-01
        • 2020-08-16
        • 2015-04-18
        相关资源
        最近更新 更多