Monse Aleman Monse Aleman -3 years ago 99
R Question

Max or min depending on another variable

I need to calculate the max and min of the wave height according to the direction from which it comes, that is to say, I have two variables:

  • Hs (wave height)

  • Direction (direction of the swell)

And I need to know the maximum wave height for waves with a direction between 11.25 and 33.75 degrees.

For now, use the function:

Max (Hs [Direction [11.25: 33.75]))

But I do not agree the result with the data that I have.

Answer Source

The answer from @LAP is absolutely correct, but you can also use the dplyr package to get both the max and min.

First let's create some sample data.

df <- data.frame(Hs = rnorm(327), Direction = runif(327, 0, 364))

Now let's calculate.


df %>%
  filter(Direction >= 11.25 & Direction <= 33.75) %>% 
  summarise(max(Hs), min(Hs))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download