我有一个字母和日期的数据框:
Dates <- data.frame(X = c("A", "B", "C", "D"), Y = c("1/1/1988","1/1/2000","11/1/1996", "2/1/1990"))
Dates$Y <- as.Date(Dates$Y, "%m/%d/%Y")
我试图将此数据框转换为对称矩阵,其中矩阵中的值是所有可能的字母组合的日期之间的绝对差(以年为单位)。所以输出将如下所示:
Output <- matrix(c(0, 12.01, 8.84, 12.01, 0, 3.17, 8.84, 3.17, 0), nrow=3, ncol=3,
dimnames = list(c("A", "B", "C"),
c("A", "B", "C")))
提前非常感谢您!
最佳答案
我们可以使用 outer
以及我们的自定义函数来计算日期差异(以年为单位)。
outer(Dates$Y, Dates$Y, FUN = function(x,y)
round(abs(as.numeric(difftime(x, y, unit="weeks"))/52.25), 2))
# [,1] [,2] [,3] [,4]
#[1,] 0.00 11.98 8.82 2.08
#[2,] 11.98 0.00 3.16 9.90
#[3,] 8.82 3.16 0.00 6.74
#[4,] 2.08 9.90 6.74 0.00
计算日期差异的代码取自 here .
正如 @thelatemail 在评论中提到的,如果我们删除 之外的
abs
、除法和 round
函数,它可能会更高效(也更整洁)外层
abs(outer(Dates$Y, Dates$Y, difftime, units="weeks") / 52.25)
关于r - 将日期数据帧转换为R中的时差对称矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49992421/