R为每个人选择最新日期行

时间:2020-06-22 18:45:30

标签: r

我在R中有一个数据框,其值如下:

    Individual     Date            Score
      A          2019/07/01         10
      A          2019/06/01         5
      B          2019/06/01         8
      C          2019/08/01         8
      C          2019/06/01         5

我想过滤每个人的最新分数。

    Individual     Date            Score
      A          2019/07/01         10
      B          2019/06/01         8
      C          2019/08/01         8

我不确定实现这一目标的最有效方法。

谢谢您的帮助

4 个答案:

答案 0 :(得分:3)

假设您的数据存储在名为df的data.frame中。我们可以使用dplyr

df %>%
  group_by(Individual) %>%
  slice_max(Date)

结果

# A tibble: 3 x 3
# Groups:   Individual [3]
  Individual Date       Score
  <chr>      <date>     <dbl>
1 A          2019-07-01    10
2 B          2019-06-01     8
3 C          2019-08-01     8

答案 1 :(得分:1)

在基本R中

do.call(rbind,lapply(split(df,df$Individual), function(x) x[which.max(as.Date(x$Date)),]))

  Individual       Date Score
A          A 2019/07/01    10
B          B 2019/06/01     8
C          C 2019/08/01     8

或者如果日期已经很整齐,我们可以简化为

do.call(rbind,lapply(split(df,df$Individual), function(x) x[1,]))

数据

df <- structure(list(Individual = structure(c(1L, 1L, 2L, 3L, 3L), .Label = c("A", 
"B", "C"), class = "factor"), Date = structure(c(2L, 1L, 1L, 
3L, 1L), .Label = c("2019/06/01", "2019/07/01", "2019/08/01"), class = "factor"), 
    Score = c(10L, 5L, 8L, 8L, 5L)), class = "data.frame", row.names = c(NA, 
-5L))

答案 2 :(得分:1)

使用data.table

library(data.table)
setDT(df)[, .SD[which.max(as.IDate(Date))], Individual]
#   Individual       Date Score
#1:          A 2019/07/01    10
#2:          B 2019/06/01     8
#3:          C 2019/08/01     8

数据

df <- structure(list(Individual = structure(c(1L, 1L, 2L, 3L, 3L), .Label = c("A", 
"B", "C"), class = "factor"), Date = structure(c(2L, 1L, 1L, 
3L, 1L), .Label = c("2019/06/01", "2019/07/01", "2019/08/01"), class = "factor"), 
    Score = c(10L, 5L, 8L, 8L, 5L)), class = "data.frame", row.names = c(NA, 
-5L))

答案 3 :(得分:0)

Base R替代品

index <- tapply(1:nrow(df), df$Individual, function(x) x[which.max(as.Date(df[x, "Date"]))])
df[index, ]

  Individual       Date Score
1          A 2019/07/01    10
3          B 2019/06/01     8
4          C 2019/08/01     8

您还可以将此工作流程与多个分组变量一起使用;只需将tapply的第二个参数替换为要分组的变量子集即可(例如df[c("Individual", "Type")],而不是df$Individual)。