删除重复项,保留具有最大绝对值的条目 [英] Remove duplicates keeping entry with largest absolute value

查看:14
本文介绍了删除重复项,保留具有最大绝对值的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有四个样本:id=1、2、3 和 4,每个样本都有一个或多个测量值:

Let's say I have four samples: id=1, 2, 3, and 4, with one or more measurements on each of those samples:

> a <- data.frame(id=c(1,1,2,2,3,4), value=c(1,2,3,-4,-5,6))
> a
  id value
1  1     1
2  1     2
3  2     3
4  2    -4
5  3    -5
6  4     6

我想删除重复项,每个 ID 只保留一个条目 - 值"列的绝对值最大的条目.也就是说,这就是我想要的:

I want to remove duplicates, keeping only one entry per ID - the one having the largest absolute value of the "value" column. I.e., this is what I want:

> a[c(2,4,5,6), ]
  id value
2  1     2
4  2    -4
5  3    -5
6  4     6

我如何在 R 中做到这一点?

How might I do this in R?

推荐答案

首先.按顺序排序,将不太需要的项目放在我要的组中

First. Sort in the order putting the less desired items last within I’d groups

 aa <- a[order(a$id, -abs(a$value) ), ] #sort by id and reverse of abs(value)

然后:删除 Id 组中第一个之后的项目

Then: Remove items after the first within I’d groups

 aa[ !duplicated(aa$id), ]              # take the first row within each id
  id value
2  1     2
4  2    -4
5  3    -5
6  4     6

这篇关于删除重复项,保留具有最大绝对值的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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