r - 我的数据框中每个组的最大单调增加/减少是多少?
问题描述
我有一个数据框,其中有我的“线性”变量的值,并且有 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
解决方案
另一种方法可以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
推荐阅读
- mysql - MySQL UNION ALL 与大型数据库上的多重 SELECT 性能
- python - Python Selenium 在浏览器关闭时检测
- java - 如何使用来自其他元素值的条件编辑 xml
- java - 如何在 JavaFX Linechart 中绘制单独的数据子范围?
- html - e.target.value 不适用于 React 输入类型 = 按钮
- r - R:如何在给定不同数据帧(训练集)的值的情况下标准化一个数据帧(测试集)
- jquery - 保存输入文本中的编辑数据并删除 readOnly 属性
- javascript - 如何在 Pug 中定义内联变量
- image - 使用 Texteditor 进行主动存储?
- javascript - 是否有任何可能的保存 web html 并从中恢复?