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

如何基于重复值筛选DataFrame?R语言实操问题求助

解决方法

你需要保留的是x列中出现次数≥2的所有行,以下是两种基于dplyr的可行方案:

方法一:用add_count快速标记并筛选

library(dplyr)

# 原始数据框
df <- data.frame(x = c(1,1,2,2,3,4),
                 y = LETTERS[1:6] )

# 筛选逻辑:先给每个x分组添加出现次数,再保留次数≥2的行
df_filtered <- df %>%
  add_count(x) %>%
  filter(n >= 2) %>%
  select(-n)  # 移除临时生成的计数列

print(df_filtered)

方法二:先提取符合条件的x值再筛选

library(dplyr)

df <- data.frame(x = c(1,1,2,2,3,4),
                 y = LETTERS[1:6] )

# 先找出出现次数≥2的x值
target_x <- df %>%
  count(x) %>%
  filter(n >= 2) %>%
  pull(x)

# 根据目标x值筛选行
df_filtered <- df %>%
  filter(x %in% target_x)

print(df_filtered)

两种方法运行后都会得到你期望的输出:

x y
1 1 A
2 1 B
3 2 C
4 2 D

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:25:00