将期限转换为数字格式

Converting maturities to numeric format

我正在尝试创建一个函数来将看起来很奇怪的到期日替换为数字:

对于可重现的示例:以下块包含数据。

dict <- c("ON","TN","1W","1M","2M","3M","6M","9M","1Y","1Y3M","1Y6M","1Y9M","2Y","2Y3M", "2Y6M","2Y9M","3Y","3Y3M","3Y6M","3Y9M","4Y","4Y3M","4Y6M","4Y9M","5Y","5Y3M","5Y6M","5Y9M","6Y","6Y3M","6Y6M","6Y9M","7Y","7Y3M","7Y6M","7Y9M","8Y","8Y3M","8Y6M","8Y9M","9Y","9Y3M","9Y6M","9Y9M","10Y","11Y","12Y","13Y","14Y","15Y","20Y","25Y","30Y","40Y","50Y")

我试着这样想:

我是运行这段代码。它正确地提取了 Y 之后的值。虽然它不适用于 10Y 11Y 12Y 13Y 14Y 15Y 20Y 25Y...有人可以提供支持吗?

sub("*.Y", "", dict)

我们可以用 str_replace_all 替换子字符串,然后 evaluate

library(stringr)
setNames(sapply(trimws(str_replace_all(dict, c("ON" = "0",
    "TN" = "1/365", "W" = "*1/52", "M"="*1/12", "Y" = "*1+")), 
    whitespace = "\+"), function(x) eval(parse(text = x))), dict)

-输出

          ON           TN           1W           1M           2M           3M           6M           9M           1Y         1Y3M 
 0.000000000  0.002739726  0.019230769  0.083333333  0.166666667  0.250000000  0.500000000  0.750000000  1.000000000  1.250000000 
        1Y6M         1Y9M           2Y         2Y3M         2Y6M         2Y9M           3Y         3Y3M         3Y6M         3Y9M 
 1.500000000  1.750000000  2.000000000  2.250000000  2.500000000  2.750000000  3.000000000  3.250000000  3.500000000  3.750000000 
          4Y         4Y3M         4Y6M         4Y9M           5Y         5Y3M         5Y6M         5Y9M           6Y         6Y3M 
 4.000000000  4.250000000  4.500000000  4.750000000  5.000000000  5.250000000  5.500000000  5.750000000  6.000000000  6.250000000 
        6Y6M         6Y9M           7Y         7Y3M         7Y6M         7Y9M           8Y         8Y3M         8Y6M         8Y9M 
 6.500000000  6.750000000  7.000000000  7.250000000  7.500000000  7.750000000  8.000000000  8.250000000  8.500000000  8.750000000 
          9Y         9Y3M         9Y6M         9Y9M          10Y          11Y          12Y          13Y          14Y          15Y 
 9.000000000  9.250000000  9.500000000  9.750000000 10.000000000 11.000000000 12.000000000 13.000000000 14.000000000 15.000000000 
         20Y          25Y          30Y          40Y          50Y 
20.000000000 25.000000000 30.000000000 40.000000000 50.000000000