Reputation: 11
So essentially I have 3 vectors that look like this
observation date (1, 2, 3, 1, 2) yields (0.05, 0.06, 0.01, 0.02, 0.04) maturities (3, 3, 4, 5, 3)
Each yield is associated with a particular observation date. Take the first yield for example, on day 1, a bond with 0.05 yield has 3 years left in maturity.
I am trying to create a matrix that has rows in observation dates and columns in maturity length; then fill in the matrix with yields. The difficult part for me is figuring out how to put the yield in the right spot, because on some observation date or maturity length, yields may not exist. I am wondering if there is a mechanism that can help me to reference the observation date and maturity and directly find the yield for me. Any thoughts would be appreciated!
Upvotes: 1
Views: 176
Reputation: 78947
1. General approach: You can create a matrix in base 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. How to create a matrix with vectors of different length:
## 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)
Upvotes: 1
Reputation: 85
Try this below code segment. You will need tidyverse package to be installed on your machine.
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
Upvotes: 0