R语言 沿着向量找到的唯一值的计数器

k97glaaz  于 2022-12-25  发布在  其他
关注(0)|答案(2)|浏览(133)

首先,我想说的是,我已经为这个基本问题找了很多答案,但似乎没有一个答案能解决这个问题。2如果这个问题已经有了答案,请原谅。
我想统计数据中行为的发生次数。

mydata <- data.frame(BH=c(
"sniff","explore","walking","explore","walking","trotting","sniff","explore","trotting","trotting","walking","walking","walking","watch","walking","trotting","watch","walking","walking","walking"))

输出必须是这样的

myoutput <- data.frame(
BH=c(
"sniff","explore","walking","explore","walking","trotting","sniff","explore","trotting","trotting","walking","walking","walking","watch","walking","trotting","watch","walking","walking","walking"),
mycount=c(
1,2,3,3,3,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5))

我曾经尝试过使用dplyr包中的ave和n_distinct,但是我只得到了给定行为的计数,而不是累积计数。
关于如何解决这个问题任何帮助或提示都将是感激的。
斯特夫

5q4ezhmt

5q4ezhmt1#

使用group-by操作和cumsum很容易做到这一点。我喜欢使用包data. table。

library(data.table)
setDT(mydata)
mydata[, mycount := c(1, rep(0, .N - 1)), by = BH] #first occurences
mydata[, mycount := cumsum(mycount)]

all.equal(setDF(mydata), myoutput)
#[1] TRUE
wz1wpwve

wz1wpwve2#

这里有一个tidyverse的解-不像罗兰的解那样简洁,但它是有效的。

library(tidyverse)

x <- mydata |> 
  mutate(rn = row_number())
  
x |> 
  group_by(BH) |> 
  mutate(id = cur_group_id()) |> 
  ungroup() |> 
  pivot_wider(names_from = BH, 
              values_from = id, 
              values_fill = 0) |> 
  mutate(across(
    sniff:watch, ~ cumsum(.x) > 0, .names = "{.col}_temp"),
    mycount = rowSums(across(ends_with('_temp')))
    ) |>
  dplyr::select(c(rn:watch, mycount)) |> 
  right_join(x, by = 'rn') |> 
  pivot_longer(-c(rn, mycount, BH)) |> 
  filter(value !=0) |> 
  dplyr::select(BH, mycount)
#> # A tibble: 20 × 2
#>    BH       mycount
#>    <chr>      <dbl>
#>  1 sniff          1
#>  2 explore        2
#>  3 walking        3
#>  4 explore        3
#>  5 walking        3
#>  6 trotting       4
#>  7 sniff          4
#>  8 explore        4
#>  9 trotting       4
#> 10 trotting       4
#> 11 walking        4
#> 12 walking        4
#> 13 walking        4
#> 14 watch          5
#> 15 walking        5
#> 16 trotting       5
#> 17 watch          5
#> 18 walking        5
#> 19 walking        5
#> 20 walking        5

相关问题