finding the index of a max value in R

后端 未结 4 2069
醉话见心
醉话见心 2020-12-10 01:57

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           


        
相关标签:
4条回答
  • 2020-12-10 02:08

    Here's a plyr solution, just because someone will say it if I don't...

    R> ddply(surge, "StormID", function(x) x[which.max(x$Surge),])
      MeshID StormID Rate Surge Wind
    1      4    1412  0.1  0.12    0
    2      1    1413  0.1  0.06    0
    
    0 讨论(0)
  • 2020-12-10 02:16

    If you have 2 data.points at the maximum, which.max will only refer to the first one. A more complete solution would involve rank:

    # data with a tie for max  
    surge <- data.frame(MeshID=c(1:7,1:4),StormID=c(rep(1412,7),
    rep(1413,4)),Surge=c(0.01,0.03,0.09,0.12,0.02,0.02,0.07,0.06,0.02,0.05,0.06))
    
    # compute ranks  
    surge$rank <- ave(-surge$Surge,surge$StormID,FUN=function(x) rank(x,ties.method="min"))
    # subset on the rank  
    subset(surge,rank==1)
       MeshID StormID Surge rank
    4       4    1412  0.12    1
    8       1    1413  0.06    1
    11      4    1413  0.06    1
    
    0 讨论(0)
  • 2020-12-10 02:19

    here is another data.table solution, but not relying on .SD (thus 10x faster)

    surge[,grp.ranks:=rank(-1*surge,ties.method='min'),by=StormID]
    surge[grp.ranks==1,]
    
    0 讨论(0)
  • 2020-12-10 02:23

    And a data.table solution for coding elegance

    library(data.table)
    surge <- as.data.table(surge)
    surge[, .SD[which.max(surge)], by = StormID]
    
    0 讨论(0)
提交回复
热议问题