Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

r - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...