r - 使用 R (dplyr) 在过滤器中实现“至少”条件
问题描述
这个问题与我之前的帖子有关: 连续超出阈值和 R 中的附加条件
这是数据:
dat <- structure(list(V1 = c(-3.85326, -2.88262, -4.1405, -3.95193,
-6.68925, -2.04202, -2.47597, -4.91161, -2.5946, -2.82873, 2.68839,
-4.1287, -4.50296, -0.143476, -1.12174, -0.756168, -1.67556,
-1.92704, -1.89279, -2.37569, -5.71746, -2.7247, -4.12986, -2.29769,
-1.52835, -2.63623, -2.31461, 2.32796, 4.14354, 4.47055, -0.557311,
-0.425266, -2.37455, -5.97684, -5.22391, 0.374004, -0.986549,
2.36419, 0.218283, 2.66014, -3.44225, 3.46593, 1.3309, 0.679601,
5.42195, 10.6555, 8.34144, 1.64939, -1.64558, -0.754001, -4.77503,
-6.66197, -4.07188, -1.72996, -1.15338, -8.05588, -6.58208, 1.32375,
-3.69241, -5.23582, -4.33509, -7.43028, -3.57103, -10.4991, -8.68752,
-8.98304, -8.96825, -7.99087, -8.25109, -6.48483, -6.09004, -7.05249,
-4.78267)), class = "data.frame", row.names = c(NA, -73L))
我想要的是
我想获得满足以下修改条件的第一个时间步:
[1] V1 > 0 at the time step
[2] In the succeeding FOUR time steps (including the timestep in [1]), V1 > 0 in AT LEAST THREE timesteps
[3] Accumulated value of the next FOUR timesteps (including the timestep in [1]) should be greater than 1.
这是到目前为止的脚本:
library(dplyr)
newx <- dat %>% as_tibble() %>%
mutate(time = 1: n()) %>%
filter(V1 > 0, dplyr::lead(V1, 1) > 0, dplyr::lead(V1, 2) > 0,
(dplyr::lead(V1, 1) + dplyr::lead(V1, 2) + dplyr::lead(V1, 3) +
dplyr::lead(V1, 4)) > 1)
输出
> newx
# A tibble: 7 x 2
V1 time
<dbl> <int>
1 2.33 28
2 2.36 38
3 3.47 42
4 1.33 43
5 0.680 44
6 5.42 45
7 10.7 46
问题
我不知道如何正确实现第二个条件。它应该检查四分之三的时间步长是否> 0。连续与否无关紧要。
预期产出
正确答案应该是 28。
我会感谢任何帮助。
解决方案
如果我理解正确并且您想要满足您条件的第一行,您可以使用zoo::rollsum
:
library(zoo)
library(dplyr)
dat %>%
rownames_to_column() %>%
filter(V1 > 0 &
rollsum(V1 > 0, 4, fill = NA, align = "left") >= 3 &
rollsum(V1, 4, fill = NA, align = "left") > 1) %>%
slice(1)
rowname V1
1 28 2.32796
推荐阅读
- php - TCPDF 如何在 HTML 中编写 PHP 代码
- javascript - Promise 不应该是异步的
- sql - 如何在雅典娜的字符串数据类型上提取月份名称
- cypress - 无法启动 Cypress Runner
- python - Azure 哨兵的 MISP 威胁指标 - Python 脚本问题
- python - 将 TensorFlow 代码移植到 Keras 的问题
- java - 在这种情况下是否需要构建器模式?
- java - 1、2、3步的第n步组合数‽
- monitoring - 无法监控 Cloudera Manager 上的 impala 查询
- javascript - 如何在复选框中与输入类型同步日志