gpt4 book ai didi

r - r-为每个组选择最后n次出现

转载 作者:行者123 更新时间:2023-12-04 16:43:52 26 4
gpt4 key购买 nike

情况

我有一个数据框df:

df <- structure(list(person = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
3L, 3L), .Label = c("pA", "pB", "pC"), class = "factor"), date = structure(c(16071,
16102, 16130, 16161, 16071, 16102, 16130, 16071, 16102), class = "Date")), .Names = c("person",
"date"), row.names = c(NA, -9L), class = "data.frame")

> df
person date
1 pA 2014-01-01
2 pA 2014-02-01
3 pA 2014-03-01
4 pA 2014-04-01
5 pB 2014-01-01
6 pB 2014-02-01
7 pB 2014-03-01
8 pC 2014-01-01
9 pC 2014-02-01

问题

如何为每个人选择按日期排序的最后2个(或'n')条目,这样我就得到了一个数据框 df1:
> df1
person date
1 pA 2014-03-01
2 pA 2014-04-01
3 pB 2014-02-01
4 pB 2014-03-01
5 pC 2014-01-01
6 pC 2014-02-01



我试过组合
library(dplyr)
df1 <- df %>%
group_by(person) %>%
select(tail(df, 2))

没有喜悦。

最佳答案

您可以尝试slice

library(dplyr)
df %>%
group_by(person) %>%
arrange(date, person) %>%
slice((n()-1):n())
# person date
#1 pA 2014-03-01
#2 pA 2014-04-01
#3 pB 2014-02-01
#4 pB 2014-03-01
#5 pC 2014-01-01
#6 pC 2014-02-01

或代替最后一步
   do(tail(., 2))

关于r - r-为每个组选择最后n次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28190779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com