使用dplyr按组获取累积计数

时间:2016-06-03 18:09:04

标签: r dplyr

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

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

再次感谢。

3 个答案:

答案 0 :(得分:5)

我们可以按'人'使用分组,然后通过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

或使用factor并将levels指定为'邻域'中的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

答案 1 :(得分:4)

使用rleid包中的frankdata.table函数也可轻松实现此目的:

library(data.table)
# with 'rleid'
setDT(df)[, moved := rleid(neighborhood)-1, by = person]
# with 'frank'
setDT(df)[, moved := frank(neighborhood, ties.method='dense')-1, by = person]

结果:

> df
    person neighborhood moved
 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,您可以使用dense_rank功能:

library(dplyr)
df %>%
  group_by(person) %>%
  mutate(moved = dense_rank(neighborhood)-1)

答案 2 :(得分:0)

这也可以使用dplyr的窗口函数来实现。这是代码:

library(dplyr)
my.df <- tbl_df(df)

my.df %>% 
    # Per person
    group_by(person) %>% 
    # sort by neighborhood
    arrange(neighborhood) %>%
    # if the neighborhood has changed compared to the row before
    mutate(moved = (neighborhood != lag(neighborhood))) %>%
    # turn NAs (first rows) into FALSE
    mutate(moved = ifelse(is.na(moved), FALSE, moved)) %>%
    # use cumulative sum of the logical column to get number of moves
    mutate(no_moves = cumsum(moved))