【问题标题】:Filtering column based on matching conditions in another column根据另一列中的匹配条件过滤列
【发布时间】:2020-05-28 02:06:58
【问题描述】:

我正在尝试使用 dplyr 执行简单的过滤,但它似乎不适用于我想做的事情。

我想基于时间过滤数据帧作为示例,仅当时间与category匹配时,然后查看列Value

df <- read.table(header = TRUE, text = "SubjectID Treatment Time Value
                A1 Amutant T0 5.3
                B0 Control T0 4.8
                A3 Amutant T3 4
                B1 Control T1 3
                B3 Control T3 6.5
                C2 Bmutant T2 2
                C1 Bmutant T1 3")

df %>% 
  group_by (Time) %>% 
  filter (Time == "T0") %>%
  filter (Value <5)

这似乎不是我真正想要得到的,因为我想对匹配 T0&lt;5 的整行进行子集化。

结果应该只过滤掉那些T0高于5但不影响T1、T2、T3的受试者。

提前致谢!

【问题讨论】:

  • 也许你只是在寻找这样的东西:df %&gt;% filter (Time == "T0", Value &lt;5)
  • 但我只需要查看 Time==“T0” 的值

标签: r filter dplyr


【解决方案1】:

如果我理解正确你可以使用子集函数

subset(df, Time == "T0" & Value < 5 | Time != "T0")

dplyr

df %>% filter(Time == "T0" & Value < 5 | Time != "T0")

【讨论】:

  • 和我上面的回复类似,我只需要根据不影响其他时间值的T0进行过滤。
  • 最后一条语句可以简化为df %&gt;% filter(Time != "T0" | Value &lt; 5)
  • 您能否更详细地解释一下出现了什么问题?由于代码现在从 T0 中删除了值 > 5 的值,而其他值仍然存在。
  • 我认为它确实可以查看数据集,非常感谢!!! :)
【解决方案2】:

创建一个可以过滤的辅助字段可能是最简单的方法

library(dplyr)

df %>%
  mutate(isFilter = case_when(Time == "T0" & Value > 5 ~ 1, TRUE ~ 0)) %>%
  filter(isFilter == 0)

SubjectID Treatment Time Value isFilter
1        B0   Control   T0   4.8        0
2        A3   Amutant   T3   4.0        0
3        B1   Control   T1   3.0        0
4        B3   Control   T3   6.5        0
5        C2   Bmutant   T2   2.0        0
6        C1   Bmutant   T1   3.0        0

【讨论】:

  • 如果你只测试一个条件,你不妨使用基础ifelse;更好的是:isFilter = as.numeric(Time == "T0" &amp; Value &gt; 5)
【解决方案3】:

我认为这会奏效。

dates <- rep(
  seq(as.numeric(as.Date("01-01-2020", format = "%d-%m-%Y")),
      as.numeric(as.Date("01-10-2020", format = "%d-%m-%Y"))), 
  each = 24
)

value <- runif(length(dates), 1, 10)
time <- runif(length(dates), 0, 1) 

data <- cbind(dates, value, time)
data <- tibble::as_tibble(data)

out <- data %>% filter(value != 0 & time > 5)
isTRUE(sum(out$time < 5 | out$value == 0) == 0)
#[1] TRUE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2020-12-08
    相关资源
    最近更新 更多