如何将Tibble按V列的增减趋势拆分为两个Tibble?
拆分先增后降的Tibble解决方案
你的问题出在原来的代码只对比了V列的首尾值,完全没考虑中间的峰值位置,所以才会把所有行都标记为下降。要正确拆分,核心是先定位V列的峰值点,再以此为界分割数据。
方法一:直接定位峰值位置(适合单峰数据)
首先构造示例数据:
library(tibble) library(dplyr) raw <- tibble( t = 1:8, V = c(2, 3, 4, 5, 6, 4, 3, 2) )
找到V列最大值对应的行索引(如果有多个相同峰值,取最后一个):
peak_idx <- raw %>% filter(V == max(V)) %>% pull(t) %>% last()
基于峰值索引拆分两个tibble:
# 增长阶段(包含峰值) tibble_increasing <- raw %>% filter(t <= peak_idx) # 下降阶段 tibble_decreasing <- raw %>% filter(t > peak_idx)
运行后得到的结果完全符合你的期望:
Tibble 1(增长阶段):
| t | V |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 4 | 5 |
| 5 | 6 |
Tibble 2(下降阶段):
| t | V |
|---|---|
| 6 | 4 |
| 7 | 3 |
| 8 | 2 |
方法二:通过阶段标记拆分(兼容小幅波动的情况)
如果数据在增长阶段有偶尔持平的情况,可以用lag()函数判断每一行是否处于增长阶段,再标记分组:
raw <- raw %>% mutate( # 判断当前值是否大于等于前一个值(第一行默认算增长) is_increasing = V >= lag(V, default = first(V)), # 累计统计下降次数,0次的为增长阶段,之后都是下降阶段 phase = ifelse(cumsum(!is_increasing) == 0, "Increasing", "Decreasing") ) # 拆分并移除辅助列 tibble_increasing <- raw %>% filter(phase == "Increasing") %>% select(-is_increasing, -phase) tibble_decreasing <- raw %>% filter(phase == "Decreasing") %>% select(-is_increasing, -phase)
这个方法能更灵活地处理非严格持续增长的单峰数据。
内容的提问来源于stack exchange,提问作者Kieran
相关产品推荐
相关产品推荐

