【问题标题】:Difficulty performing arithmetic with dates in R在 R 中难以用日期执行算术运算
【发布时间】:2014-01-04 21:56:18
【问题描述】:

我正在处理包含日期的数据并且遇到了一些麻烦。本质上,我希望根据两个现有日期和另一个变量为我的数据框中的所有行计算一个新日期。例如,我希望能够从 Date1 中减去 10 天,或者计算 Date1 和 Date2 之间的日期等。但是,在将新的计算日期添加到数据框时,我无法理解类分配。示例数据框:

#  Uncomment to clear your session...
# rm(list = ls(all = TRUE))
tC <- textConnection("StudyID   Date1   Date2
C0031   2-May-09    12-Jan-10
C0032   7-May-09    30-Apr-10")
data <- read.table(header=TRUE, tC)
close.connection(tC)
rm(tC)

#CONVERTING TO DATES    
data$Date1 <- with(data,as.Date(Date1,format="%d-%b-%y"))
data$Date2 <- with(data,as.Date(Date2,format="%d-%b-%y"))

我的问题从这里开始

class(data[1, "Date2"] - 10) # class is "Date". So far so good. 
data[1, "newdate"]  <- (data[1, "Date2"] - 10)
class(data[1, "newdate"]) # class is now "numeric"... 

尝试过

data[1, "newdate"]  <- as.Date(data[1, "Date2"] - 10)
class(data[1, "newdate"]) # doesn't help. Class still "numeric"... 

只是不明白为什么这个值在分配给数据时变成数字

【问题讨论】:

  • 你试过data$newdate &lt;- data$Date1 - 10吗?我认为问题在于回收单个值。由于列必须具有相同的长度,因此您的奇异日期值将被回收以匹配 data.frame 中的行数。我假设(我会检查)回收条属性从而将日期转换为它们的数字形式。

标签: r time date-arithmetic


【解决方案1】:

问题是由于不存在列 newdate 以及分配单个值:

# create a single value in a new column
data[1, "newdate"]  <- data[1, "Date2"] - 10
class(data[1, "newdate"]) # numeric 

# create the whole column
data[ , "newdate2"] <- data[1, "Date2"] - 10
class(data[1, "newdate2"]) # Date

# create a column of class Date before assigning value
data[ , "newdate3"] <- as.Date(NA)
data[1, "newdate3"] <- data[1, "Date2"] - 10
class(data[1, "newdate3"]) # Date

顺便说一句,在对Date 对象执行数学运算时,您不需要as.Date

【讨论】:

    【解决方案2】:

    问题是由于回收了矢量剥离属性。正如我在评论中所说,使用例如data$newdate &lt;- data$Date1 - 10创建整列而不回收向量,从而保留Date等属性。考虑下面的说明性玩具示例:

    # Simple vector with an attribute
    x <- 1:3
    attributes(x) <- list( att = "some attributes" )
    x
    #[1] 1 2 3
    #attr(,"att")
    #[1] "some attributes"
    
    # Simple data.frame with 3 rows
    df <- data.frame( a = 1:3 )
    
    #  New column using first element of vector with attributes
    df$b <- x[1]
    
    #  It is recycled to correct number of rows and attributes are stripped
    str(df$b)
    # int [1:3] 1 1 1
    
    #  Without recycling attributes are retained
    df$c <- x
    str(df$c)
    # atomic [1:3] 1 2 3
    # - attr(*, "att")= chr "some attributes"
    
    #  But they all look the same...
    df
    #  a b c
    #1 1 1 1
    #2 2 1 2
    #3 3 1 3
    

    根据您的数据..

    attributes(data$Date1)
    # $class
    # [1] "Date"
    

    【讨论】:

    • 感谢您提供这两个很好的答案,一个是实用的,另一个是剖析潜在行为。非常感谢,现在不卡了!
    猜你喜欢
    • 2013-05-16
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    相关资源
    最近更新 更多