问题
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.
回答1:
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))])
回答2:
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))
来源:https://stackoverflow.com/questions/45713534/max-or-min-depending-on-another-variable