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

R语言如何查找数据框每列的唯一值并生成对应标记列

实现方案

核心逻辑为逐列统计所有值的出现频次,若当前行对应值的频次为1则标记对应列名,否则填充NA,两种实现方案可选:

方案1:tidyverse 简洁实现

适合习惯使用tidy系列工具的场景,代码可读性高:

# 构造样例数据
df <- structure(list(X = c("Row1", "Row2", "Row3", "Row4", "Row5",  "Row6", "Row7"), Col1 = c(0L, 1L, 1L, 0L, 1L, -1L, 0L), Col2 = c(1L,  0L, 1L, 1L, 1L, 0L, -2L), Col3 = c(-1L, 0L, 1L, 0L, 0L, 1L, 1L )), class = "data.frame", row.names = c(NA, -7L))
rownames(df) <- df$X
df <- df[, -1]

# 生成标记列
library(dplyr)
res <- df %>%
  mutate(across(everything(),
                ~ ifelse(table(.)[as.character(.)] == 1, cur_column(), NA),
                .names = "{col}_uni"))

方案2:Base R 无依赖实现

不需要加载任何第三方包,运行效率高,适合纯基础R的使用场景:

# 构造样例数据同上
df <- structure(list(X = c("Row1", "Row2", "Row3", "Row4", "Row5",  "Row6", "Row7"), Col1 = c(0L, 1L, 1L, 0L, 1L, -1L, 0L), Col2 = c(1L,  0L, 1L, 1L, 1L, 0L, -2L), Col3 = c(-1L, 0L, 1L, 0L, 0L, 1L, 1L )), class = "data.frame", row.names = c(NA, -7L))
rownames(df) <- df$X
df <- df[, -1]

# 遍历列生成标记列
for (col in colnames(df)) {
  col_freq <- table(df[[col]])
  df[[paste0(col, "_uni")]] <- ifelse(col_freq[as.character(df[[col]])] == 1, col, NA)
}

两种方案运行后得到的结果均与你给出的预期结构完全匹配,针对数千行的小数据量场景运行效率完全足够。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:06:03