Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

dataframe - finding the index of a max value in R

I have the following data frame called surge:

MeshID    StormID Rate Surge Wind
1         1412 1.0000E-01   0.01 0.0
2         1412 1.0000E-01   0.03 0.0
3         1412 1.0000E-01   0.09 0.0
4         1412 1.0000E-01   0.12 0.0
5         1412 1.0000E-01   0.02 0.0
6         1412 1.0000E-01   0.02 0.0
7         1412 1.0000E-01   0.07 0.0
1         1413 1.0000E-01   0.06 0.0
2         1413 1.0000E-01   0.02 0.0
3         1413 1.0000E-01   0.05 0.0

I used the following code to find the max value of surge per storm:

MaxSurge <- data.frame(tapply(surge[,4], surge[,2], max))

It returns:

1412 0.12
1413 0.06

This is great, except I'd also like it to include the MeshID value at the point where the surge is the maximum. I know I can probably use which.max, but I can't quite figure out how to put this in action. I'm VERY new to R programming.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

And a data.table solution for coding elegance

library(data.table)
surge <- as.data.table(surge)
surge[, .SD[which.max(surge)], by = StormID]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...