dplyr过滤器似乎在for循环中不起作用

时间:2019-02-19 21:39:36

标签: r for-loop filter dplyr

我有很多列想要删除3个特定值。我想在for循环中进行。但是由于某种原因,它不起作用,我不知道为什么。函数如下:

for (i in colnames(df1)){
    z <- as.name(i)
    df1 <- df1 %>% filter(z != "Refusal") %>% filter(z != "Don't know") %>%  filter(z != "No answer")
}

我知道变量z不是必需的,但我希望它可以有所帮助。没有。

这是每列代码的完整示例。这可行,但是很烦人的解决方案

df1 <- data.frame(country = df$cntry, gender = df$gndr, pplfair = df$pplfair,
                  gincdif = df$gincdif, happy = df$happy, sclmeet = df$sclmeet,
                  inprdsc = df$inprdsc, sclat = df$sclact, rlgbg = df$rlgblg, 
                  dfincac = df$dfincac, sblazy = df$sblazy, eduyrs = df$eduyrs,
                  imprich = df$imprich, iprspot = df$iprspot, impfun = df$impfun)

##Wrangling data

###from data removing no answer, don't know, refusal
df1 <- df1 %>% filter(pplfair != "Refusal") %>% filter(pplfair != "Don't know") %>%  filter(pplfair != "No answer")

df1 <- df1 %>% filter(gincdif != "Refusal") %>% filter(gincdif != "Don't know") %>%  filter(gincdif != "No answer")

df1 <- df1 %>% filter(happy != "Refusal") %>% filter(happy != "Don't know") %>%  filter(happy != "No answer")

df1 <- df1 %>% filter(sclmeet != "Refusal") %>% filter(sclmeet != "Don't know") %>%  filter(sclmeet != "No answer")

df1 <- df1 %>% filter(inprdsc != "Refusal") %>% filter(inprdsc != "Don't know") %>%  filter(inprdsc != "No answer")

df1 <- df1 %>% filter(sclat != "Refusal") %>% filter(sclat != "Don't know") %>%  filter(sclat != "No answer")

df1 <- df1 %>% filter(rlgbg != "Refusal") %>% filter(rlgbg != "Don't know") %>%  filter(rlgbg != "No answer")

df1 <- df1 %>% filter(dfincac != "Refusal") %>% filter(dfincac != "Don't know") %>%  filter(dfincac != "No answer")

df1 <- df1 %>% filter(sblazy != "Refusal") %>% filter(sblazy != "Don't know") %>%  filter(sblazy != "No answer")

df1 <- df1 %>% filter(eduyrs != "Refusal") %>% filter(eduyrs != "Don't know") %>%  filter(eduyrs != "No answer")

df1 <- df1 %>% filter(imprich != "Refusal") %>% filter(imprich != "Don't know") %>%  filter(imprich != "No answer")

df1 <- df1 %>% filter(iprspot != "Refusal") %>% filter(iprspot != "Don't know") %>%  filter(iprspot != "No answer")

df1 <- df1 %>% filter(impfun != "Refusal") %>% filter(impfun != "Don't know") %>%  filter(impfun != "No answer")

我将非常感谢您的任何建议。

1 个答案:

答案 0 :(得分:3)

使用filter_all%in%可以大大简化OP的代码:

library(dplyr)

df1 %>% 
  filter_all(any_vars(!(. %in% c("Refusal", "Don't know", "No answer"))))

或使用filter_at(如果它是所有列的子集):

df1 %>% 
  filter_at(vars(varnames), any_vars(!(. %in% c("Refusal", "Don't know", "No answer"))))