仅取r中数据帧中所有列的重复id的最大值



我有24525行22列的数据帧。最后一列是ID列,其他都是数字。唯一id个数为18414,部分id重复超过2次

我需要删除重复的ID,并在另一个数据帧中只保留每个ID和每个列的最大值。

我尝试在for循环中对每个列进行排序,并删除重复项以保持最大值,但它不起作用,我不确定。

有人知道做这个任务的方法吗?

提前谢谢你

虚假数据:

mt <- mtcars
mt$cyl <- as.character(mt$cyl)

基地R

aggregate(. ~ cyl, data = mt, FUN = max)
#   cyl  mpg  disp  hp drat    wt  qsec vs am gear carb
# 1   4 33.9 146.7 113 4.93 3.190 22.90  1  1    5    2
# 2   6 21.4 258.0 175 3.92 3.460 20.22  1  1    5    6
# 3   8 19.2 472.0 335 4.22 5.424 18.00  0  1    5    8

(感谢@GregorThomas在这方面的调整)

tidyverse

library(dplyr)
mt %>%
  group_by(cyl) %>%
  summarize_all(max)
# # A tibble: 3 x 11
#   cyl     mpg  disp    hp  drat    wt  qsec    vs    am  gear  carb
#   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 4      33.9  147.   113  4.93  3.19  22.9     1     1     5     2
# 2 6      21.4  258    175  3.92  3.46  20.2     1     1     5     6
# 3 8      19.2  472    335  4.22  5.42  18       0     1     5     8

更新:根据@akrun的建议,dplyr::summarize_all已被取代。来自?summarize_all:

限定动词(_if, _at, _all)已被across()在现有动词中的使用所取代。详情见vignette("colwise")

更新代码:

mt %>%
  group_by(cyl) %>%
  summarize(across(everything(), max))
# # A tibble: 3 x 11
#   cyl     mpg  disp    hp  drat    wt  qsec    vs    am  gear  carb
#   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 4      33.9  147.   113  4.93  3.19  22.9     1     1     5     2
# 2 6      21.4  258    175  3.92  3.46  20.2     1     1     5     6
# 3 8      19.2  472    335  4.22  5.42  18       0     1     5     8

data.table

library(data.table)
setDT(mt)
mt[, lapply(.SD, max), by=.(cyl)]

最新更新