如何按 A 列在 R 中生成唯一值并在 B 列中保留最大值的行 [英] How to make a unique in R by column A and keep the row with maximum value in column B

查看:33
本文介绍了如何按 A 列在 R 中生成唯一值并在 B 列中保留最大值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多列 (17) 的 data.frame.第 2 列有几行具有相同的值,我只想保留其中的一行,特别是第 17 列中具有最大值的行.

I have a data.frame with several columns (17). Column 2 have several rows with the same value, I want to keep only one of those rows, specifically the one that has the maximum value in column 17.

例如:

A    B
'a'  1
'a'  2
'a'  3
'b'  5
'b'  200

Would return
A    B
'a'  3
'b'  200

(加上其余的列)

到目前为止,我一直在使用 unique 函数,但我认为它会随机保留一个或只保留出现的第一个.

So far I've been using the unique function, but I think it randomly keeps one or keeps just the first one that appears.

** 更新 **真实数据有376000行.我已经尝试了 data.table 和 ddply 建议,但它们需要永远.任何想法最有效?

** UPDATE ** The real data has 376000 rows. I've tried the data.table and ddply suggestions but they take forever. Any idea which is the most efficient?

推荐答案

使用包data.table的解决方案:

set.seed(42)
dat <- data.frame(A=c('a','a','a','b','b'),B=c(1,2,3,5,200),C=rnorm(5))
library(data.table)

dat <- as.data.table(dat)
dat[,.SD[which.max(B)],by=A]

   A   B         C
1: a   3 0.3631284
2: b 200 0.4042683

这篇关于如何按 A 列在 R 中生成唯一值并在 B 列中保留最大值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆