为什么`difftime` 带有R 中其他变量的标签属性?

问题描述

在下面的示例中,我使用 Hmisc(可以是 labelled 包无关紧要)为日期变量创建标签。在第二个数据集中,我使用 difftime 来计算两个日期之间的差异。当您在新列上运行属性时,日期标签(提供给 difftime 的第一个变量将被保留。为什么要保留此属性

library(Hmisc)


trial <- data.frame(dates = seq(as.Date("1970-01-01"),as.Date("1970-01-01")+199,1),dates2 = sample(seq(as.Date('1999/01/01'),as.Date('2000/01/01'),by="day"),200))

Hmisc::label(trial$dates) <- "New Date"


trial2 <- transform(trial,difftimer = difftime(dates,dates2))
attributes(trial2$difftimer)

解决方法

difftime 调用 .difftime,源代码为

.difftime
function (xx,units,cl = "difftime") 
{
    class(xx) <- cl
    attr(xx,"units") <- units
    xx
}

它只是在现有属性之外添加/更新属性,即 classunits。更改在 class 中,因为它正在分配给新的

attributes(trial$dates2) # // starts with class only attributes
#$class
#[1] "Date"

attributes(.difftime(trial$dates2,units = 'secs')) # //updated class
#$class
#[1] "difftime"

#$units # // added new attribute
#[1] "secs"

对于“日期”列,“标签”有两个类和一个属性

attributes(trial$dates)
#$class
#[1] "labelled" "Date"    

#$label
#[1] "New Date"

attributes(.difftime(trial$dates,units = 'secs')) 
#$class #// changed class
#[1] "difftime"

#$label #// this attribute is untouched
#[1] "New Date"

#$units
#[1] "secs"