%>%的多个条件

时间:2019-01-31 12:41:14

标签: r conditional magrittr

这似乎是应该在stackoverflow / google中的问题,但不是(或至少我找不到),所以我在这里问:

可复制的示例:

colnames(df)
"Z1"   "Z2"   "Z3"   "GV1"  "GV2"  "GV3"  "GV4"  "GV5"  "GV6"  "GV7"  "GV8"  "GV9" "GVY"  "EN1" "EN2"  "EN3"  "EN4"  "EN5"  "EN6"  "EN7"  "EN8"  "EN9"  "ENY"  "PV1"  "PV2"  "PV3"  "PV4"  "PV5"  "PV6"  "PV7"  "PVY" 

我正在尝试理解/执行下一个代码:

colnames(df[substr(colnames(df),start=1,stop=2) == "GV" & substr(colnames(df),start=3,stop=3) != "Y"])

我喜欢使用magrittr管道运算符%>%将它用于更易读的代码(这可行):

library(magrittr)
df %>%
  colnames %>%
    substr(start=1,stop=2) == "GV"

但是,这样做没有意义(这不起作用)

df %>%
  colnames %>%
    substr(start=1,stop=2) == "GV" & substr(colnames(df),start=3,stop=3) != "Y"]

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

如果您的目标是简化代码,则可以使用正则表达式:

# Match string that starts with GV and is not fallowed by Y
grep("^GV[^Y]", foo, value = TRUE)
# [1] "GV1" "GV2" "GV3" "GV4" "GV5" "GV6" "GV7" "GV8" "GV9"

# Data
foo <- c("Z1", "Z2", "Z3", "GV1", "GV2", "GV3", "GV4", "GV5", "GV6", "GV7", "GV8", "GV9", "GVY", "EN1", "EN2", "EN3", "EN4", "EN5", "EN6", "EN7", "EN8", "EN9", "ENY", "PV1", "PV2", "PV3", "PV4", "PV5", "PV6", "PV7", "PVY")

答案 1 :(得分:0)

我想举一个可重复的示例,也就是说,您是否尝试过拆分过滤器?

df %>%
  colnames %>%
    substr(start=1,stop=2) == "GV"  %>%
       substr(colnames(df),start=3,stop=3) != "Y"

答案 2 :(得分:0)

使用@Pogibas的数据,您可以使用{这样编写命令:

foo %>% {substr(.,start=1,stop=2) == "GV" & substr(.,start=3,stop=3) != "Y"}
# [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
# [19] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE