【问题标题】:R - Display row with biggest value in a new dataframe [duplicate]R - 在新数据框中显示具有最大值的行[重复]
【发布时间】:2018-07-07 15:19:55
【问题描述】:

我有一个像这样的数据框:

x1= c("Station1", "Station2", "Station3", "Station4", "Station5", "Station6", "Station7", "Station8", "Station9", "Station10")
x2= seq(-2,10 , length=10)
x3= seq(30, 45, length=10)
x4= c(1, 3, 2, 1, 4, 2, 4, 3, 3, 1)
x5= seq(10, 100, length=10)
df = data.frame(Station=x1, Lon=x2, Lat=x3, Number=x4, Size=x5)

>df
    Station        Lon      Lat Number Size
1   Station1 -2.0000000 30.00000      1   10
2   Station2 -0.6666667 31.66667      3   20
3   Station3  0.6666667 33.33333      2   30
4   Station4  2.0000000 35.00000      1   40
5   Station5  3.3333333 36.66667      4   50
6   Station6  4.6666667 38.33333      2   60
7   Station7  6.0000000 40.00000      4   70
8   Station8  7.3333333 41.66667      3   80
9   Station9  8.6666667 43.33333      3   90
10 Station10 10.0000000 45.00000      1  100

站点分为 4 个不同的组,可以在 $Number 列中看到。现在我想在每个组的 df$Size 列中提取具有最大值的站。所以我想要一个新的数据框,它有 4 行(每组一个)和相同的列。

应该是这样的:

    Station        Lon      Lat Number Size
6   Station6  4.6666667 38.33333      2   60
7   Station7  6.0000000 40.00000      4   70
9   Station9  8.6666667 43.33333      3   90
10 Station10 10.0000000 45.00000      1  100

我已经尝试过这样来获取行号,但它不起作用。

index1 = df$Number=="1" 
index2 = df$Number=="2" 
index3 = df$Number=="3" 
index4 = df$Number=="4" 

df[index1][which.max(df$Size),]

有什么想法吗?

【问题讨论】:

标签: r indexing subset extract


【解决方案1】:

那就是:

library(dplyr)
library(magrittr)

df %>%
  group_by(Number) %>%
  arrange(desc(Size)) %>%
  top_n(1)

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    相关资源
    最近更新 更多