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

Why does `difftime` carry label attribute from other variable in 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
}

它只是 adding/updating 个属性,即 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"

对于 'dates' 列,有两个 类 和 'label'

的属性
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"