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

在R语言中如何筛选指定行中值相同的列?

在R中找出指定行内值一致的列

问题背景

你有一个包含字符型值(0、1、2、3、4、5、?、-)的dataframe,需要筛选出指定行(如示例中的第3、4、5行)中所有值完全相同的列,示例预期返回x6、x7、x8。

示例数据集构造

首先重现你的示例数据:

df <- data.frame(
  x1 = c("0", "1", "2", "3", "4"),
  x2 = c("5", "?", "1", "?", "0"),
  x3 = c("1", "1", "3", "4", "1"),
  x4 = c("1", "2", "2", "1", "?"),
  x5 = c("1", "5", "1", "1", "1"),
  x6 = c("?", "5", "3", "3", "3"),
  x7 = c("0", "1", "?", "?", "?"),
  x8 = c("5", "-", "?", "?", "?"),
  row.names = 1:5,
  stringsAsFactors = FALSE
)

基础实现方法(Base R)

无需额外包,用Base R即可完成:

# 定义目标行
target_rows <- 3:5

# 筛选符合条件的列
result_cols <- names(df)[apply(df[target_rows, ], 2, function(col) length(unique(col)) == 1)]

# 输出结果
result_cols
# [1] "x6" "x7" "x8"
  • df[target_rows, ]:提取指定的目标行子集。
  • apply(..., 2, ...):按列遍历目标行数据。
  • length(unique(col)) == 1:判断该列在目标行中的所有值是否唯一(即完全相同)。
  • names(df)[...]:提取符合条件的列名。

Tidyverse风格实现(dplyr)

如果你习惯使用tidyverse工具链,可以用dplyr包:

library(dplyr)

target_rows <- 3:5

result_cols <- df %>%
  slice(target_rows) %>%
  summarise(across(everything(), ~n_distinct(.) == 1)) %>%
  select(where(~.)) %>%
  names()

result_cols
# [1] "x6" "x7" "x8"
  • slice(target_rows):选择目标行。
  • summarise(across(everything(), ~n_distinct(.) == 1)):对每列计算是否仅含唯一值,得到布尔结果。
  • select(where(~.)):筛选出结果为TRUE的列。
  • names():提取最终的列名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:10:26