Anakin Skywalker
Anakin Skywalker

Reputation: 2520

Filtering in dplyr based on certain conditions

I have a simple dataframe

name <- c("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
type <- c("Terrestrial planet", "Terrestrial planet", "Terrestrial planet", 
      "Terrestrial planet", "Gas giant", "Gas giant", "Gas giant", "Gas giant")
diameter <- c(0.382, 0.949, 1, 0.532, 11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03, 0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)

df_space <- data.frame(name, type, diameter, rotation, rings)

How to filter planets, which have a bigger diameter than Earth.

I tried

df_space %>% filter(diameter > df_space[df_space$name == "Earth"])

but it does not work. Any elegant solution for tidyverse?

Upvotes: 1

Views: 64

Answers (2)

zx8754
zx8754

Reputation: 56249

After subsetting for "Earth", you need to choose the column "diameter":

df_space %>%
  filter(diameter > df_space[ df_space$name == "Earth", "diameter" ])

Note: This answer just shows why your code didn't work, @arg0naut91's solution is more dplyry and should be the right answer.

Upvotes: 3

arg0naut91
arg0naut91

Reputation: 14774

You're looking for:

filter(df_space, diameter > diameter[name == 'Earth'])

Output:

     name      type diameter rotation rings
1 Jupiter Gas giant   11.209     0.41  TRUE
2  Saturn Gas giant    9.449     0.43  TRUE
3  Uranus Gas giant    4.007    -0.72  TRUE
4 Neptune Gas giant    3.883     0.67  TRUE

Upvotes: 3

Related Questions