【问题标题】:Count consecutive observations within grouped data in R计算 R 中分组数据中的连续观察值
【发布时间】:2020-03-18 12:01:50
【问题描述】:

我有一个看起来像这样的数据框

id year
1  2000
2  2000
1  2001
3  2001
4  2002
5  2002
6  2002
5  2003
6  2003
4  2004
5  2004

我想逐步计算我的数据框中连续出现了多少年 ID。换句话说我想得到

id year count
1  2000 1
2  2000 1
1  2001 2
3  2001 1
4  2002 1
5  2002 1
6  2002 1
5  2003 2
6  2003 2
4  2004 1
5  2004 3

你有什么建议吗?非常感谢, 马可

【问题讨论】:

  • 试试with(df, ave(year, id, FUN = seq_along))
  • 为什么4 2004 1 是正确的?不应该是4 2004 2
  • 这是rle 类型的答案。这可能是所选重复项的重复位
  • @VitaliAvagyan 不,它应该是 1,因为之前的观察不是在前一年(即 2003 年),而是两年前(即 2002 年)。只有当 id 确实出现在随后的两年中时,我才想将 obs 计为连续的。
  • 试试with(DF, ave(year, id, FUN = function(x) {print(diff(x) != 1); ave(x, c(0, cumsum(diff(x)!= 1)), FUN = seq_along)}))

标签: r


【解决方案1】:

这是一个基本答案:

with(DF, ave(year, id, FUN = function(x) ave(x, c(0, cumsum(diff(x)!= 1)), FUN = seq_along)))

回答:

library(data.table)
setDT(DF)
DF[, 
   count := rowid(rleid(c(0, cumsum(diff(year) != 1)))),
   by = id][]

还有:

library(dplyr)

DF %>% 
  group_by(id) %>%
  group_by(rle_id = c(0, cumsum(diff(year) != 1)), add = T)%>%
  mutate(count = row_number())%>%
  ungroup()

数据:

DF <- 
  read.table(text = 'id year
1  2000
2  2000
1  2001
3  2001
4  2002
5  2002
6  2002
5  2003
6  2003
4  2004
5  2004', header = T)

【讨论】:

    【解决方案2】:

    这个对一个非常相似的问题的回答是一个很好的解决方案。

    https://stackoverflow.com/a/52820446/2862791

    
    library(tibble)
    library(dplyr)
    
    
    cumcount <- function(x){
    
            #' Credit to SO user `Gaurav Bansal``
            cumcount <- numeric(length(x))
            names(cumcount) <- x
    
            for(i in 1:length(x)){
                    cumcount[i] <- sum(x[1:i]==x[i])
            }
    
            return(cumcount)
    }
    
    
    t <- tibble(
            id = c(1, 2, 1, 3, 4, 5, 6, 5, 6, 4, 5), 
            year = c(2000, 2000, 2001, 2001, 2002, 2002, 
                     2002, 2003, 2003, 2004, 2004)
    
    )
    
    
    t %>% 
            group_by(id) %>%
            mutate(count = cumcount(id))
    
         id  year count
       <dbl> <dbl> <dbl>
     1     1  2000     1
     2     2  2000     1
     3     1  2001     2
     4     3  2001     1
     5     4  2002     1
     6     5  2002     1
     7     6  2002     1
     8     5  2003     2
     9     6  2003     2
    10     4  2004     2
    11     5  2004     3
    
    

    【讨论】:

    • 感谢您的回答。但是 2004 年的 id 4 应该是 1,因为之前对 id==4 的观察不是在前一年(即 2003 年),而是两年前(即 2002 年)。只有当 id 确实出现在随后的两年中时,我才想将 obs 计为连续的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多