[英]Find whether current date is same as previous date
I have these date times: 我有这些约会时间:
library(lubridate)
my_date_times <- dmy_hm(c("17/05/16 23:49", "17/05/16 09:39", "08/08/16 23:21", "08/12/16 09:23", "26/02/17 08:03", "12/10/17 12:04", "12/10/17 10:03"))
I want to calculate whether a date is the same as the date in the previous row. 我想计算日期是否与上一行中的日期相同。 If the current date is the same as the previous, then I would to add TRUE to both rows in the
same_date
variable. 如果当前日期与前一个日期相同,那么我将在TRUE中将TRUE添加到
same_date
变量的两行中。 I'm not concerned if the two times do not match. 我不在乎两次是否不匹配。 Hopefully this code explains what I'm after.
希望这段代码可以说明我的要求。
same_date <- c(TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE)
library(tibble)
df <- data_frame(my_date_times, same_date)
df
# A tibble: 7 x 2
my_date_times same_date
<dttm> <lgl>
1 2016-05-17 23:49:00 TRUE
2 2016-05-17 09:39:00 TRUE
3 2016-08-08 23:21:00 FALSE
4 2016-12-08 09:23:00 FALSE
5 2017-02-26 08:03:00 FALSE
6 2017-10-12 12:04:00 TRUE
7 2017-10-12 10:03:00 TRUE
The OP has requested to add TRUE
to both rows if the current date is the same as the previous. 如果当前日期与前一个日期相同,则OP要求将
TRUE
添加到两行 。 This is why the diff()
approach won't work here. 这就是为什么
diff()
方法在这里不起作用的原因。
Instead, we can group by date and check whether the group consists only of one row or multiple rows. 相反,我们可以按日期分组并检查该分组是仅包含一行还是包含多行。
library(data.table)
setDT(df)[, same_date := .N > 1, by = as.Date(my_date_times)][]
my_date_times same_date 1: 2016-05-17 23:49:00 TRUE 2: 2016-05-17 09:39:00 TRUE 3: 2016-08-08 23:21:00 FALSE 4: 2016-12-08 09:23:00 FALSE 5: 2017-02-26 08:03:00 FALSE 6: 2017-10-12 12:04:00 TRUE 7: 2017-10-12 10:03:00 TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.