简体   繁体   English

查找当前日期是否与上一个日期相同

[英]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.

相关问题 在R中具有相同列类别的数据框中查找以前的日期 - Find previous date in dataframe with same column category in R 当我使用滞后 function 时,如何“跳过”与当前行中的日期相同的前行中的日期? - When I use the lag function, how do I "skip" dates in previous rows that are the same as the date in the current row? 在r中查找满足条件的上一个日期 - Find the previous date that meets a condition in r 从R中的当前日期获取上个月的开始日期和结束日期 - Getting previous month start date and end date from current date in R 创建循环以查找当前日期和下面行日期之间的差异 - Create loop to find difference between current date and date of row below 使用 timeDate 库从当前日期提取上个月 - Extract previous month from current date using timeDate library 查找特定日期是否是星期五的期权到期-timeDate程序包有问题 - Find whether a particular date is an Option Expiration Friday - problem with timeDate package 通过基于当前日期和前一个日期的子集从数据框中提取值 - Extract values from data frame by subsetting based on current date and previous date 数据框中类别的上一个日期到同一类别的下一行 - Previous date for category in data frame into next row of the same category 使用 R 中的 data.table 查找上周的最后日期 - Find last date of previous week using data.table in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM