列中的计数值使用空单元格表示新数字

Count values in column use empty cells to indicate new number

我想使用行为数据来计算捕获的项目数。这是我的示例数据:

df <- data.frame(id = as.factor(c(51,51,51,51,51,51,51,52,52,52,52,52,52)), 
             type = c("(K)","(K)","(K)","(K)","","","","(K)","(K)","","(K)","","(K)"))

我想根据它们是否连续来计算我的每个 "K"。如果是连续的,则该字符串应计为一个。如果两者之间有差距,它们都应该算作一个..所以最终的总数将是 2。

希望这是有道理的...对于上面的例子,我希望我的最终输出数据看起来像这样

id type tally
1 51  (K)     1
2 52  (K)     3

我认为聚合可能会这样做,但它计算的是一列中的总数,所以 51 tally=4 而不是 1

任何帮助将不胜感激

谢谢 恩典

我们可以尝试使用 data.table 中的 rleid。将'data.frame'转换为'data.table'(setDT(df)),按'id'分组,找到'type'的运行-length-id,按[分组=25=] 和 'type',获取 'val' 的 unique 个元素中不为空白的 length

library(data.table)
setDT(df)[, val := rleid(type), id][type!="", .(tally = uniqueN(val)), .(id, type)]
#   id type tally
#1: 51  (K)     1
#2: 52  (K)     3

或者我们可以使用tidyverse

library(tidyverse)
df %>%
   mutate(val = cumsum(type != lag(type, default = type[1])))  %>% 
   group_by(id) %>% 
   filter(type!="") %>% 
   summarise(type = first(type), tally= n_distinct(val))
# A tibble: 2 × 3
#      id   type tally
#   <fctr> <fctr> <int>
#1     51    (K)     1
#2     52    (K)     3

在基础 R 中,您可以使用 rle 来完成。首先将 df 拆分为 id,然后为每个子组计算 "(K)".

的时间序列数
sapply(split(df, df$id), function(a)
    length(with(rle(as.character(a$type)), lengths[values == "(K)"])))
#51 52 
# 1  3 

基础 R 中的 rle 命令会很有用。

temp<- tapply(df$type, df$id, function(x) rle(x == "(K)"))
df.new<- data.frame(id = names(temp), 
                tally = unlist(lapply(temp, function(x) sum(x$values))))