Max or min depending on another variable

2019-09-21 07:26发布

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.

2条回答
Melony?
2楼-- · 2019-09-21 08:01

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.

library(dplyr)

df %>%
  filter(Direction >= 11.25 & Direction <= 33.75) %>% 
  summarise(max(Hs), min(Hs))
查看更多
聊天终结者
3楼-- · 2019-09-21 08:18

Assume your dataframe is called df, your variables are called Hs and Direction, you can use

max(df$Hs[df$Direction >= 11.25 & df$Direction <= 33.75])

to get the maximum of all Hs values within the defined value range of Direction.

If you, like me, dislike the necessity to define both lower and upper bounds of the interval separately, you can use this neat function (which I found here):

in_interval <- function(x, interval){
   stopifnot(length(interval) == 2L)
   interval[1] < x & x < interval[2]
}

Then use

max(df$Hs[in_interval(df$Direction, c(11.25, 33.75))])
查看更多
登录 后发表回答