【问题标题】:How can I find the difference between two dates in the factor? [duplicate]如何找到因子中两个日期之间的差异? [复制]
【发布时间】:2017-10-04 01:55:49
【问题描述】:

我有一个名为“enrolments”的数据框:

enrolled_at、unenrolled_at 和fully_participated_at 是因素。我想在我的数据框中添加一个新列,以指示两个非空属性之间的小时差异。这个新列的类型并不重要,但它必须以这种格式(HH MM SS)显示时间。

我想做以下伪代码:

If (unenrolled_at == empty && fully_participated_at != empty) 
    newAttributeValue = fully_participated_at - enrolled_at
else if (unenrolled_at != empty && fully_participated_at == empty)
    newAttributeValue = unenrolled_at - enrolled_at
else
    do nothing

编辑:我尝试了站点中的所有方法来执行此操作,但它们不起作用。在我的数据框中存储为因子类的时间,但站点中的解决方案是因子 - 因子或(字符串)时间 - (字符串)时间。我还分别尝试了“as.character”和“as.Date”函数。所以我的问题不是重复的。 Rolando Tamayo 提供了不同的方法来解决我的问题,但它给了我错误:“ymd_hms(cmets$unenrolled_at) 中的错误:找不到函数“ymd_hms””(我安装了 lubridate 包)

【问题讨论】:

  • 请将您的数据包含为可编辑文本,而不是图像
  • 先用as.character转成字符,再用as.Date转成日期格式
  • 我在问问题之前尝试过,但它给出了这个错误: charToDate(x) 中的错误:字符串不是标准的明确格式 --- 尝试过的命令:difftime(as.Date(as .character(enrolments$unenrolled_at)) - as.Date(as.character(enrolments$enrolled_at)))

标签: r format as.date


【解决方案1】:

你可以使用包lubridate:

library(lubridate)


#Create a df with dates

df<-tibble::tibble(
  enrolled_at=as.factor(c("2002-06-09 12:45:40 UTC","2003-01-29 09:30:40 UTC",
                         "2002-09-04 16:45:40 UTC")),
 unenrolled_at=as.factor(c("2002-11-13 20:00:40 UTC",
                        "2002-07-07 17:30:40","2002-07-07 17:30:40 UTC")))
df

# A tibble: 3 x 2
              enrolled_at           unenrolled_at
                   <fctr>                  <fctr>
1 2002-06-09 12:45:40 UTC 2002-11-13 20:00:40 UTC
2 2003-01-29 09:30:40 UTC     2002-07-07 17:30:40
3 2002-09-04 16:45:40 UTC 2002-07-07 17:30:40 UTC

#Check Class
class(df$enrolled_at)

[1] "factor"

#Check class after function ymd_hms
class(ymd_hms(df$enrolled_at))

[1] "POSIXct" "POSIXt"

#Calculete de difference in days
dif<-ymd_hms(df$ unenrolled_at)-ymd_hms(df$enrolled_at)

#difference like a period
as.period(dif)

 [1] "157d 7H 15M 0S"    "-205d -16H 0M 0S"  "-58d -23H -15M 0S"

#Add as a column in df
df$newAttributeValue<-as.period(ymd_hms(df$ unenrolled_at)-ymd_hms(df$enrolled_at))

df

# A tibble: 3 x 3
              enrolled_at           unenrolled_at newAttributeValue
                   <fctr>                  <fctr>      <S4: Period>
1 2002-06-09 12:45:40 UTC 2002-11-13 20:00:40 UTC    157d 7H 15M 0S
2 2003-01-29 09:30:40 UTC     2002-07-07 17:30:40  -205d -16H 0M 0S
3 2002-09-04 16:45:40 UTC 2002-07-07 17:30:40 UTC -58d -23H -15M 0S

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2011-06-24
    • 1970-01-01
    • 2014-03-15
    相关资源
    最近更新 更多