使用 dplyr 按组获取累积计数

编程入门 行业动态 更新时间:2024-10-24 18:17:53
本文介绍了使用 dplyr 按组获取累积计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Thanks in advance. I have the following data:

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"))

我想生成一个新列,该列提供每个人随着面板的进行移动经过的社区的累积计数.像这样:

I would like to generate a new column that gives the cumulative count of neighborhoods that each person moves through as the panel progresses. Like such:

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',然后通过 matching 'neighborhood' 和它的 unique 值以获取索引并减去 1.

We can use group by 'person', then create the 'moved' by matching the 'neighborhood' with its unique values to get the index and subtract 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

或使用 factor 和 levels 指定为 'neighborhood' 中的 unique 值,强制为 'integer' 并减去 1.

or use factor with levels specified as the unique values in 'neighborhood', coerce to 'integer' and subtract 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

更多推荐

使用 dplyr 按组获取累积计数

本文发布于:2023-11-22 08:24:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:dplyr

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!