【问题标题】:Why does `difftime` carry label attribute from other variable in R?为什么`difftime`带有R中其他变量的标签属性?
【发布时间】:2021-02-26 20:27:02
【问题描述】:

在下面的示例中,我使用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)

【问题讨论】:

    标签: r hmisc difftime


    【解决方案1】:

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-24
      • 2021-11-23
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      • 2012-04-28
      • 2018-07-26
      相关资源
      最近更新 更多