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

R语言如何筛选data.frame中仅含指定值和NA的列

R 筛选符合取值要求的data.frame列方法

核心逻辑:遍历每一列,验证该列所有非NA值均属于允许的取值集合c(1,2,3,4,5),保留满足条件的列即可。

方法1:原生R实现(无需安装额外包)

# 示例数据
x = data.frame(col1 = c("a" , "b", "d", "e", "f", "g"), 
           col2 = c(12, 45, 235, 2134, NA, 1), 
           col3 = c(1, 2, 3, 1, 2, NA), 
           col4 = c(1, 2, 3, 4, 5, NA), 
           col5 = c(1, 2, 3, 4, 5, 6))

# 定义允许的取值
allowed <- c(1,2,3,4,5)
# 筛选列
result <- x[, sapply(x, function(col) {
  all(col[!is.na(col)] %in% allowed)
})]

运行后得到的result仅包含col3、col4两列,和预期结果一致。

方法2:dplyr 语法实现(适合tidyverse生态用户)

library(dplyr)

allowed <- c(1,2,3,4,5)
result <- x %>%
  select(where(~ all(.x[!is.na(.x)] %in% allowed)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:24:05