我有一个字符列表:
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,但无论如何都会很棒!)
您可以使用-
df$plant[df$animal %in% list]
#[1] "tree" "daisy" "grass"
你可以试试
anmal <- c("dog", "cat", "fish")
df %>%
filter(animal %in% anmal) %>%
pull(plant)
[1] "tree" "daisy" "grass"