R语言如何筛选列名存在于指定列表中的dataframe列
R 数据框列筛选问题与解法
问题描述
我按如下方式生成了单词列表:
exString = "hello words are cool words are neat" wordList = unique(unlist(str_split(exString, ' '))) wordList # 输出结果:"hello" "words" "are" "cool" "neat"
我需要用这个单词列表,筛选数据框中列名和列表内单词一致的列。示例数据框生成代码如下:
hello <- c(1,2,3) words <- c(4,5,6) cactus <- c(7,8,9) exDataframe <- data.frame(hello, words, cactus) # 原始数据框结构: # hello words cactus # 1 4 7 # 2 5 8 # 3 6 9
因为hello和words在wordList中,最终筛选得到的数据框只需要保留这两列,预期输出如下:
# hello words # 1 4 # 2 5 # 3 6
解法
你可以选择以下任意一种方案实现需求:
- 基础R原生实现,无需额外依赖:
result_df <- exDataframe[, colnames(exDataframe) %in% wordList]
- tidyverse生态下dplyr实现,容错性更强:
library(dplyr) result_df <- exDataframe %>% select(any_of(wordList))
any_of()参数会自动跳过wordList中不在数据框列名里的元素,不会触发报错,适合单词列表和数据框列名匹配度不确定的场景。
内容的提问来源于stack exchange,提问作者mk2080
相关产品推荐
相关产品推荐

