21

我有以下数据框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

我使用以下代码来查找每次风暴的浪涌最大值:

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

它返回:

1412 0.12
1413 0.06

这很好,除了我还希望它包含MeshID浪涌最大值处的值。我知道我可能可以使用which.max,但我不太清楚如何将其付诸实践。我对 R 编程很陌生。

4

4 回答 4

14

data.table以及编码优雅的解决方案

library(data.table)
surge <- as.data.table(surge)
surge[, .SD[which.max(surge)], by = StormID]
于 2012-10-04T03:31:32.780 回答
13

这是另一个 data.table 解决方案,但不依赖于 .SD(因此快 10 倍)

surge[,grp.ranks:=rank(-1*surge,ties.method='min'),by=StormID]
surge[grp.ranks==1,]
于 2012-10-18T12:48:26.327 回答
7

如果您最多有 2 个 data.points,which.max则只会参考第一个。更完整的解决方案将涉及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
于 2012-10-03T13:08:31.400 回答
6

这是一个 plyr 解决方案,只是因为如果我不这样做,就会有人说...

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
于 2012-10-03T11:23:27.210 回答