如何根据来自不同列的值 select 来自一列的值?

How to select value from one column based on values from different column?

我有一个这样的字符列表:

list <- c("dog", "cat", "fish")

我有一个这样的 df:

df = tibble(animal = c("dog", "fish", "frog", "cat", "shark"), plant = c("tree", "daisy", "mushroom", "grass", "dafodil"))

print(df)

# A tibble: 5 × 2
  animal plant   
  <chr>  <chr>   
1 dog    tree    
2 fish   daisy   
3 frog   mushroom
4 cat    grass   
5 shark  dafodil

我想生成一个与上面的动物列表相对应的植物列表,它看起来像:

plant_list 
c("tree", "grass" "daisy")

我试过了

plant_list <- c()

for (i in list){
  if (df$animal == i){
    plant_list <- append(plant_list, df$plant)
  } else {}
}

但这给了我一个错误。什么是好的解决方案?(最好使用 dplyr,但无论如何都会很棒!)

你可以试试

anmal <- c("dog", "cat", "fish")
df %>%
  filter(animal %in% anmal) %>%
  pull(plant)

[1] "tree"  "daisy" "grass"

你可以使用-

df$plant[df$animal %in% list]
#[1] "tree"  "daisy" "grass"