首页 > 解决方案 > 我的数据框中每个组的最大单调增加/减少是多少?

问题描述

我有一个数据框,其中有我的“线性”变量的值,并且有 30 个不同的组。我想计算/计算数据框中每个组的值单调增加/减少的最大次数。

Linear | Series | Basal
70 | Night 1 | increase       
72 | Night 1 | increase
75 | Night 1 | decrease
65 | Night 1 | decrease
100 | Night 2 | decrease
90 | Night 2 | decrease
91 | Night 2 | increase
80 | Night 2 | decrease

结果应该是

Night 1: Increase 2 Decrease 2
Night 2: Increase 1 Decrease 2

标签: rdataframe

解决方案


另一种方法可以rle用来获得最大运行次数:

maxmv <- function(x, val) with(rle(x), max(lengths[values == val]))

df %>%
  group_by(Series) %>%
  summarise(increase = maxmv(Basal, "increase"),
            decrease = maxmv(Basal, "decrease"))   

# A tibble: 2 x 3
  Series  increase decrease
  <chr>      <int>    <int>
1 Night 1        2        2
2 Night 2        1        2

使用 base r 的相同方法:

aggregate(Basal ~ Series, df, FUN = function(y) c(increase = maxmv(y, "increase"),
                                                  decrease = maxmv(y, "decrease")))

   Series Basal.increase Basal.decrease
1 Night 1              2              2
2 Night 2              1              2

推荐阅读