You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中按Genes和intA分组获取distance列绝对值最值的完整行

问题描述

现有如下数据框:

Genes   intA    Chr_intA    Chr_intB    direction_1 direction_2 distance
GeneA   P53 chr19   chr8    -   -   -423
GeneA   P53 chr19   chr8    -   -   -3467567
GeneA   P53 chr19   chr8    -   -   10452
GeneB   P53 chr19   chr8    -   -   -2884
GeneB   P53 chr19   chr8    -   -   -40

需求:按Genes和intA列分组,分别获取distance列绝对值最大(保留原正负)的行,以及绝对值最小的行。

期望的绝对值最大输出:

Genes   intA    Chr_intA    Chr_intB    direction_1 direction_2 distance
GeneA   P53 chr19   chr8    -   -   -3467567
GeneB   P53 chr19   chr8    -   -   -2884

期望的绝对值最小输出:

Genes   intA    Chr_intA    Chr_intB    direction_1 direction_2 distance
GeneA   P53 chr19   chr8    -   -   -423
GeneB   P53 chr19   chr8    -   -   -40

尝试的代码存在两个问题:将distance的负值转为正值,且丢失了其他列数据:

library(dplyr)
df <- df %>% group_by(Genes, intA) %>% summarise(distance = max(abs(distance)))
df <- df %>% group_by(Genes, intA) %>% summarise(distance = min(abs(distance)))
解决方案

改用filter配合which.max()/which.min()定位目标行,既能保留所有列数据,又不会改变distance的原始正负值:

1. 获取每组中绝对值最大的行

library(dplyr)

df_max <- df %>%
  group_by(Genes, intA) %>%
  filter(which.max(abs(distance))) %>%
  ungroup()

2. 获取每组中绝对值最小的行

df_min <- df %>%
  group_by(Genes, intA) %>%
  filter(which.min(abs(distance))) %>%
  ungroup()

关键说明

  • which.max(abs(distance))返回每组内distance绝对值最大的行的索引,filter根据该索引筛选整行,完整保留所有列的原始数据。
  • which.min(abs(distance))同理,定位每组内distance绝对值最小的行。
  • ungroup()用于取消分组状态,方便后续对数据框进行其他操作(可选)。

内容的提问来源于stack exchange,提问作者Apex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:39:12