R: Uniques (or dplyr distinct) + 最近的日期
R: Uniques (or dplyr distinct) + most recent date
我有一个由信息行组成的数据框,这些信息包括基于不同日期的名称的重复项。我想将此 df 过滤为仅包含唯一名称的 df,但如果有机会,也选择最近出现的事件。我是 dplyr 的忠实粉丝,之前使用过 distinct 和 select 的组合,但文档显示这似乎无法单独完成:
"Variables to use when determining uniqueness. If there are multiple rows for a given combination of inputs, only the first row will be preserved."
这似乎是一个经常出现的问题,所以我想知道是否有任何人有任何建议。下面是一个 df 示例,它反映了我的真实数据具有名称作为字符 class 和日期作为我使用 lubridate 包生成的 POSIXct。
structure(list(Name = c("John", "John", "Mary", "John", "Mary",
"Chad"), Date = structure(c(1430438400, 1433116800, 1335830400,
1422748800, 1435708800, 1427846400), tzone = "UTC", class = c("POSIXct",
"POSIXt"))), .Names = c("Name", "Date"), row.names = c(NA, -6L
), class = "data.frame")
期望的结果是:
structure(list(Name = c("John", "Mary", "Chad"), Date = structure(c(1433116800,
1435708800, 1427846400), class = c("POSIXct", "POSIXt"), tzone = "UTC")), .Names = c("Name",
"Date"), row.names = c(2L, 5L, 6L), class = "data.frame")
感谢您的帮助。
最简单的方法是
DF %>% arrange(desc(Date)) %>% distinct(Name)
如果您真的希望名称保持相同的顺序,这些也可以(感谢@akrun):
DF %>% group_by(Name) %>% slice(which.max(Date)) # @akrun's better idea
DF %>% group_by(Name) %>% filter(Date==max(Date)) # my idea
我有一个由信息行组成的数据框,这些信息包括基于不同日期的名称的重复项。我想将此 df 过滤为仅包含唯一名称的 df,但如果有机会,也选择最近出现的事件。我是 dplyr 的忠实粉丝,之前使用过 distinct 和 select 的组合,但文档显示这似乎无法单独完成:
"Variables to use when determining uniqueness. If there are multiple rows for a given combination of inputs, only the first row will be preserved."
这似乎是一个经常出现的问题,所以我想知道是否有任何人有任何建议。下面是一个 df 示例,它反映了我的真实数据具有名称作为字符 class 和日期作为我使用 lubridate 包生成的 POSIXct。
structure(list(Name = c("John", "John", "Mary", "John", "Mary",
"Chad"), Date = structure(c(1430438400, 1433116800, 1335830400,
1422748800, 1435708800, 1427846400), tzone = "UTC", class = c("POSIXct",
"POSIXt"))), .Names = c("Name", "Date"), row.names = c(NA, -6L
), class = "data.frame")
期望的结果是:
structure(list(Name = c("John", "Mary", "Chad"), Date = structure(c(1433116800,
1435708800, 1427846400), class = c("POSIXct", "POSIXt"), tzone = "UTC")), .Names = c("Name",
"Date"), row.names = c(2L, 5L, 6L), class = "data.frame")
感谢您的帮助。
最简单的方法是
DF %>% arrange(desc(Date)) %>% distinct(Name)
如果您真的希望名称保持相同的顺序,这些也可以(感谢@akrun):
DF %>% group_by(Name) %>% slice(which.max(Date)) # @akrun's better idea
DF %>% group_by(Name) %>% filter(Date==max(Date)) # my idea