在最新日期之前识别组中的重复项

时间:2019-04-18 03:21:06

标签: r

我目前有一个看起来像这样的数据框:

   ID Value       Date
1   1     A   1/1/2018
2   1     B   2/3/1988
3   1     B   6/3/1994
4   2     A  12/6/1999
5   2     B 24/12/1957
6   3     A   9/8/1968
7   3     B  20/9/2016
8   3     C  15/4/1993
9   3     C   9/8/1994
10  4     A   8/8/1988
11  4     C   6/4/2001

在每个ID中,我想标识一行中有重复的Value。我要标识的Value是最近的Date的副本。

结果数据框应如下所示:

   ID Value       Date mostRecentDuplicate
1   1     A   1/1/2018                  0
2   1     B   2/3/1988                  0
3   1     B   6/3/1994                  1
4   2     A  12/6/1999                  0
5   2     B 24/12/1957                  0
6   3     A   9/8/1968                  0
7   3     B  20/9/2016                  0
8   3     C  15/4/1993                  0
9   3     C   9/8/1994                  1
10  4     A   8/8/1988                  0
11  4     C   6/4/2001                  0`

我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用dplyr,我们可以先将Date转换为实际日期值,然后将group_by IDValue转换为值1。多于1行,并且row_number与最大Date的行号相同。

library(dplyr)

df %>%
  mutate(Date = as.Date(Date, "%d/%m/%Y")) %>%
  group_by(ID, Value) %>%
  mutate(mostRecentDuplicate = +(n() > 1 & row_number() == which.max(Date))) %>%
  ungroup()


# A tibble: 11 x 4
#      ID Value Date       mostRecentDuplicate
#   <int> <fct> <date>                   <int>
# 1     1 A     2018-01-01                   0
# 2     1 B     1988-03-02                   0
# 3     1 B     1994-03-06                   1
# 4     2 A     1999-06-12                   0
# 5     2 B     1957-12-24                   0
# 6     3 A     1968-08-09                   0
# 7     3 B     2016-09-20                   0
# 8     3 C     1993-04-15                   0
# 9     3 C     1994-08-09                   1
#10     4 A     1988-08-08                   0
#11     4 C     2001-04-06                   0