gpt4 book ai didi

r - 使用 dplyr 按组获取累积计数

转载 作者:行者123 更新时间:2023-12-04 10:57:02 24 4
gpt4 key购买 nike

提前致谢。我有以下数据:

df <- data.frame(person=c(1,1,1,1,2,2,2,2,3,3,3,3), 
neighborhood=c("A","A","A","A","B","B","C","C","D","D","E","F"))

我想生成一个新列,该列提供每个人随着面板的进行移动经过的社区的累积计数。像这样:
df2 <- data.frame(person=c(1,1,1,1,2,2,2,2,3,3,3,3), 
neighborhood=c("A","A","A","A","B","B","C","C","D","D","E","F"),
moved=c(0,0,0,0,0,0,1,1,0,0,1,2)
)

再次感谢。

最佳答案

我们可以使用group by 'person',然后创建'moved' by match用它的 unique 连接“邻里”值以获取索引并减去 1。

df %>%
group_by(person) %>%
mutate(moved = match(neighborhood, unique(neighborhood))-1)
# person neighborhood moved
# <dbl> <fctr> <dbl>
#1 1 A 0
#2 1 A 0
#3 1 A 0
#4 1 A 0
#5 2 B 0
#6 2 B 0
#7 2 C 1
#8 2 C 1
#9 3 D 0
#10 3 D 0
#11 3 E 1
#12 3 F 2

或使用 factorlevels指定为 unique “邻域”中的值,强制为“整数”并减 1。
df %>%
group_by(person) %>%
mutate(moved = as.integer(factor(neighborhood, levels = unique(neighborhood)))-1)
# person neighborhood moved
# <dbl> <fctr> <dbl>
#1 1 A 0
#2 1 A 0
#3 1 A 0
#4 1 A 0
#5 2 B 0
#6 2 B 0
#7 2 C 1
#8 2 C 1
#9 3 D 0
#10 3 D 0
#11 3 E 1
#12 3 F 2

关于r - 使用 dplyr 按组获取累积计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37620926/

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