【问题标题】:Calculate & add column length_of_time from date column in R从R中的日期列计算并添加时间列长度
【发布时间】:2017-03-05 16:31:57
【问题描述】:

我正在尝试创建一个新的计算字段length_of_time。我有一列包含日期的 final_date:

2/10/2016  
4/4/2016  
5/8/2016  
10/1/2016

我正在尝试计算一个新字段,显示 2016 年 10 月 23 日和 final_date 之间的时间长度。

我尝试使用 dplyr:

mutate(df, length_of_time = 10/23/2016 - final_date) 

并收到错误:

" eval 中的错误(substitute(expr), envir, enclos) : 只能从“POSIXt”对象中减去”

然后我尝试使用:

df <- as.POSIXlt(df$final_date)

再次运行我的原始代码,却收到以下错误:

Error in UseMethod("mutate_") : 
  no applicable method for 'mutate_' applied to an object of class "c('POSIXlt', 'POSIXt')"

【问题讨论】:

    标签: r date dplyr calculated-columns posixlt


    【解决方案1】:

    您的日期格式有点混乱。 (解释见代码cmets)

    library(dplyr)
    
    df <- data.frame(final_date = c("2/10/2016","4/4/2016"))
    
    ## you need to specify the format of your date columns as it is ambiguous
    ## I've guessed you're using day/month/year
    df$final_date <- as.POSIXct(df$final_date, format = "%d/%m/%Y")
    
    ## and you need to subtract the `final_date` (which is POSIXct) 
    ## from another POSIXct object
    mutate(df, length_of_time = as.POSIXct("2016-10-23") - final_date)
    
    final_date length_of_time
    1 2016-10-02  20.95833 days
    2 2016-04-04 201.95833 days
    

    进一步阅读

    帮助了解POSIXctPOSIXlt 之间的区别、日期格式、日期计算等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-13
      • 2020-11-25
      • 2022-01-05
      • 2018-02-27
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多