使用 R 的 tidyverse,过滤掉多列中满足条件的数据的最有效方法是什么?

J.S*_*ree 0 r filter dplyr tidyverse

我有一个数据集,我想过滤掉一个人最喜欢的颜色是绿色并且他们最喜欢的食物是寿司。但是,如果此人仅满足其中一项标准,我想保留他们。在这种情况下,我如何才能最有效地转换这个数据集:

library(dplyr)

test <- tibble(person = c("Justin", "Corey", "Kate", "Sibley"),
               fav_food = c("sushi", "sushi", "cake", "tomatos"),
               fav_color = c("green", "red", "green", "blue"))
Run Code Online (Sandbox Code Playgroud)

到这个数据集?

library(dplyr)
answer <- tibble(person = c("Corey", "Kate", "Sibley"),
               fav_food = c("sushi", "cake", "tomatos"),
               fav_color = c("red", "green", "blue"))
Run Code Online (Sandbox Code Playgroud)

我当前的解决方案是创建一个新变量,它是这两列的组合,但我觉得似乎必须有一个比这更直接的解决方案:

library(dplyr)

#code works but curious if there is a more straightforward approach

test %>%
  mutate(food_color = paste(fav_food, fav_color, sep = "-")) %>%
  filter(food_color != "sushi-green")
Run Code Online (Sandbox Code Playgroud)

Maë*_*aël 5

指明您的条件,&并用 分隔,用于!保留不满足此条件的行:

\n
test %>% \n  filter(!(fav_food == "sushi" & fav_color == "green"))\n
Run Code Online (Sandbox Code Playgroud)\n

输出

\n
# A tibble: 3 \xc3\x97 3\n  person fav_food fav_color\n  <chr>  <chr>    <chr>    \n1 Corey  sushi    red      \n2 Kate   cake     green    \n3 Sibley tomatos  blue  \n
Run Code Online (Sandbox Code Playgroud)\n