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

如何在R中筛选‘0’‘1’各至少出现两次的DataFrame字符列?

在R中筛选符合条件的DataFrame列

首先构造示例数据:

df <- data.frame(
  x1 = c("0", "0", "0", "0", "0"),
  x2 = c("0", "?", "0", "?", "0"),
  x3 = c("1", "1", "1", "1", "1"),
  x4 = c("1", "0", "0", "1", "?"),
  x5 = c("1", "1", "1", "0", "1"),
  x6 = c("1", "0", "0", "0", "0"),
  x7 = c("1", "1", "1", "1", "0"),
  stringsAsFactors = FALSE
)

方法一:基础R实现(无需额外包)

直接用colSums统计每列中"0"和"1"的出现次数,再通过逻辑条件筛选列:

# 生成筛选逻辑:"0"出现≥2次且"1"出现≥2次
keep_cols <- colSums(df == "0") >= 2 & colSums(df == "1") >= 2

# 提取符合条件的列
filtered_df <- df[, keep_cols]

方法二:使用purrr包遍历列

如果你习惯用tidyverse工具链,可以用purrr::map_lgl逐列判断条件:

library(purrr)

keep_cols <- map_lgl(df, ~ sum(.x == "0") >= 2 & sum(.x == "1") >= 2)
filtered_df <- df[, keep_cols]

两种方法最终都会得到只包含x4和x5的DataFrame,完全匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:20:42