【问题标题】:Count and Assign Consecutive Occurrences of Variable计算和分配变量的连续出现
【发布时间】:2020-01-29 10:06:04
【问题描述】:

我希望计算任何值的连续出现并将该计数分配给下一列中的该值。以下是输入和期望输出的示例:

dataset <- data.frame(input = c("a","b","b","a","a","c","a","a","a","a","b","c"))
dataset$count <- c(1,2,2,2,2,1,4,4,4,4,1,1)

dataset  
   input   count
     a       1
     b       2
     b       2
     a       2
     a       2
     c       1
     a       4
     a       4
     a       4
     a       4
     b       1
     c       1

使用rle(dataset$input) 我可以获取每个值的出现次数。但我想要上述格式的结果输出。

我的问题类似于: R: count consecutive occurrences of values in a single column 但是这里的输出是按顺序排列的,我想将计数本身分配给该值。

【问题讨论】:

    标签: r count find-occurrences


    【解决方案1】:

    您可以在rle 中重复lengths 参数lengths 时间

    with(rle(dataset$input), rep(lengths, lengths))
    #[1] 1 2 2 2 2 1 4 4 4 4 1 1
    

    使用dplyr,我们可以使用lag创建组,然后统计每个组的行数。

    library(dplyr)
    
    dataset %>%
      group_by(gr = cumsum(input != lag(input, default = first(input)))) %>%
      mutate(count = n())
    

    data.table

    library(data.table)
    setDT(dataset)[, count:= .N, rleid(input)]
    

    数据

    确保input 列是字符而不是factor

    dataset <- data.frame(input = c("a","b","b","a","a","c","a","a","a","a","b","c"),
               stringsAsFactors = FALSE)
    

    【讨论】:

      【解决方案2】:

      我们可以使用rleiddplyr

      library(dplyr)
      dataset %>%
         group_by(grp = rleid(input)) %>%
         mutate(count = n())
      

      【讨论】:

        猜你喜欢
        • 2019-02-04
        • 1970-01-01
        • 2017-06-05
        • 2014-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        相关资源
        最近更新 更多