【问题标题】:Using dplyr filter with multiple conditions使用具有多个条件的 dplyr 过滤器
【发布时间】:2020-05-09 09:45:23
【问题描述】:

我有以下数据集。

共有三列:Pentad、A 和 B。

library(zoo)
library(rlang)
library(tidyverse) 

dat<-structure(list(Pentad = 50:73, A = c(152.796, 
109.678, 91.5594,115.155, 135.9, 202.441, 71.6951, 
88.3894, 261.962,135.853, 89.3425, 110.674, 100.558, 
173.507, 87.2157, 86.6425, 75.1852, 57.403, 62.5705, 
49.6846, 52.0257, 92.819, 105.419, 97.7598), 
B = c(145.402, 110.109, 83.1076, 95.3952, 148.571, 
119.178, 56.5031, 76.2635, 260.443, 109.705, 62.3749, 
100.322, 88.4134, 135.721, 63.1486, 69.7161, 62.3886, 
46.4513, 52.4546, 42.7725, 45.7643, 79.5419, 79.9434, 
87.6405)), class = "data.frame", row.names = c(NA, 
-24L))

我想在 R 中实现以下条件。

[1] V1 should be between 0 and 90 at the time step (excluding 0 and 90)

[2] In the succeeding FOUR time steps (including the 
timestep in [1]), V1 between 0 and 90 in AT LEAST THREE timesteps

到目前为止我所拥有的:

 test2 <- function(dat, column_name){ 
   dat %>%
   rownames_to_column() %>%
   filter((.data[[column_name]] > 0 & .data[[column_name]] < 90) & 
         rollsum(.data[[column_name]] > 0 & .data[[column_name]] < 90, 4, fill = NA, align = 
                   "left") >= 3) %>%
   slice(1) -> result
  return(result)
}

out <- colnames(dat2) %>% 
  set_names %>% 
  map_dfr(~ test2(dat2, .x), .id = 'Col_ID')

问题:

我想获取第二列(A 列)和第三列(B 列)的上述三个条件都为真的时间步长/pentad 值。

即两列同时满足条件的时间步长。

预期的输出是 Pentad 64。

知道如何在 R 中实现这一点吗?

我将不胜感激。

【问题讨论】:

  • 您能否在共享示例中包含您的预期输出?
  • @RonakShahI 添加了预期的输出。第一列应该是 pentad 64。
  • 它如何满足Accumulated value of the next FOUR timesteps (including the timestep in [1]) should be less than -1. ?接下来 4 个值的总和肯定大于 -1。
  • 天啊..哈哈...谢谢你指出这一点。它不包括在标准中!
  • pentad 65, 66 也满足这个条件吧?

标签: r dplyr


【解决方案1】:

这是一个非常接近 OP 的尝试。

library(dplyr)
library(zoo)

test2 <- function(dat) {
   dat %>%
      filter_at(vars(A:B), all_vars(. > 0 & . < 90 & 
                     rollsum(. > 0 & . < 90, 4, fill = NA) >= 3)) %>%
       slice(1L)
}

test2(dat)

#  Pentad       A       B
#1     64 87.2157 63.1486

【讨论】:

  • 嗨@Ronak ..如果我理解正确的话,该函数只是应用于A列。B列满足相同pentad的标准只是巧合。如果 B 列满足 65 候的标准怎么办?那么 A 列和 B 列之间的公共点现在是 pentad 65。
  • 在这种情况下,不需要传递任何列名,因为您要检查这两列。查看更新的答案。
猜你喜欢
  • 2020-04-17
  • 2019-10-10
  • 2017-10-11
  • 2019-09-21
  • 2017-05-06
  • 1970-01-01
  • 2013-01-18
  • 2018-08-11
  • 1970-01-01
相关资源
最近更新 更多