【发布时间】:2022-01-23 05:39:19
【问题描述】:
我有一个名为 fruits 的数据框,其中每行最多有 3 个具有相应颜色的水果。 Color1 与 Fruit1 搭配,Color2 与 Fruit2 搭配,Color3 与 Fruit3 搭配。
Color1 Color2 Color3 Fruit1 Fruit2 Fruit3
1 red green green apple mango kiwi
2 yellow green red banana plum mango
3 green red grape apple
4 yellow apple
使用 dplyr,我可以返回包含苹果的行(1、3 和 4)。我可以返回带有红色(1、2 和 3)的行。
red <- filter_at(fruits, vars(Color1:Color3), any_vars(. == "red"))
apple <- filter_at(fruits, vars(Fruit1:Fruit3), any_vars(. == "apple"))
但是我如何只返回红苹果,即只返回第一行(Color1 = red,Fruit1 = apple)和第三行(Color2 = red,Fruit2 = apple)?
谢谢。
附言这是表格的代码
Color1 <- c("red", "yellow", "green", "yellow")
Color2 <- c("green", "green", "red", "")
Color3 <- c("green", "red", "", "")
Fruit1 <- c("apple", "banana", "grape", "apple")
Fruit2 <- c("mango", "plum", "apple", "")
Fruit3 <- c("kiwi", "mango", "", "")
fruits <- data.frame (Color1, Color2, Color3, Fruit1, Fruit2, Fruit3)
【问题讨论】:
-
你能用
dput(.)发布你的数据吗? -
不是 dput,但这有帮助吗?
Color1 <- c("red", "yellow", "green", "yellow") Color2 <- c("green", "green", "red", "") Color3 <- c("green", "red", "", "") Fruit1 <- c("apple", "banana", "grape", "apple") Fruit2 <- c("mango", "plum", "apple", "") Fruit3 <- c("kiwi", "mango", "", "") fruits <- data.frame (Color1, Color2, Color3, Fruit1, Fruit2, Fruit3)