【发布时间】:2021-05-01 18:12:00
【问题描述】:
我有u 和time1 和time2 都以dd-mm-yyyy hh:mm 的格式列出。我想生成一个新的协变量,其中包含 u$time1 和 u$time2 之间的 hours。
他们被列为as.character
str(u)
'data.frame': 5765 obs. of 2 variables:
$ time1: chr "30-01-2020 07:20" "25-04-2019 15:05" "11-01-2019 22:01" "11-01-2019 22:01" ...
$ time2: chr "14-02-2020 15:34" "27-04-2019 10:56" "12-01-2019 00:42" "23-01-2019 10:08" ...
预期输出
> head(u)
time1 time2 new
1 30-01-2020 07:20 14-02-2020 15:34 hours between time1 and time2
2 25-04-2019 15:05 27-04-2019 10:56 hours between time1 and time2
3 11-01-2019 22:01 12-01-2019 00:42 hours between time1 and time2
4 11-01-2019 22:01 23-01-2019 10:08 hours between time1 and time2
如果小时数有一个小数点,我会更喜欢,并且最好使用dplyr 或lubridate 的解决方案。
u <- structure(list(time1 = c("30-01-2020 07:20", "25-04-2019 15:05",
"11-01-2019 22:01", "11-01-2019 22:01", "17-04-2018 07:55"),
time2 = c("14-02-2020 15:34", "27-04-2019 10:56", "12-01-2019 00:42",
"23-01-2019 10:08", "20-04-2018 11:04")), row.names = c(NA,
5L), class = "data.frame")
【问题讨论】:
-
“一个小数点” 是一个数据丢失操作。我建议您在呈现为报告之前的最后一步中这样做,而不是在处理的早期。为此,它是
round(.,0)(仍然是一个数字)或sprintf("%0.1f",.)(现在是一个字符串,此字段不再有数学)之一。
标签: r dataframe time dplyr lubridate