如何在R语言中结合starts_with()与select_if()筛选数据列?
移除指定前缀且全为0的数据列的解决方案
问题背景
需要移除列名以filler开头且所有值均为0的列,同时保留:
- 非
filler前缀的原始列 filler前缀但包含非零值的列
直接将starts_with()嵌套进select_if()会报错,因为starts_with()是tidyselect的列名选择器,只能在选择型函数(比如select())的上下文里使用,不能在select_if()的列值判断谓词中直接调用。
可行解决方案
方法1:使用select() + where()(推荐,tidyverse现代写法)
通过逻辑组合筛选列:先保留所有非filler前缀的列,再筛选出filler前缀且不全为0的列,两者合并即为目标结果。
iris %>% tibble() %>% slice(1:5) %>% mutate( fillerQ = rep(0,5), fillerW = rep(0,5), fillerE = rep(0,5), fillerR = c(0,0,1,0,0), fillerT = rep(0,5), fillerY = rep(0,5), fillerU = rep(0,5), fillerI = c(0,0,0,0,1), fillerO = rep(0,5), fillerP = rep(0,5), ) %>% select( # 保留所有非filler前缀的列 !starts_with("filler"), # 保留filler前缀且不全为0的列 starts_with("filler") & where(~ sum(abs(.)) != 0) )
方法2:通过列名索引移除目标列
先选中所有filler前缀的列,判断其中哪些全为0,再从整体中移除这些列:
iris %>% tibble() %>% slice(1:5) %>% mutate( fillerQ = rep(0,5), fillerW = rep(0,5), fillerE = rep(0,5), fillerR = c(0,0,1,0,0), fillerT = rep(0,5), fillerY = rep(0,5), fillerU = rep(0,5), fillerI = c(0,0,0,0,1), fillerO = rep(0,5), fillerP = rep(0,5), ) %>% select( everything(), # 移除filler开头且全为0的列 -starts_with("filler")[colSums(abs(.)) == 0] )
两种方法最终都会保留原始iris列,以及fillerR和fillerI这两个包含非零值的前缀列,移除其余全0的filler列。
内容的提问来源于stack exchange,提问作者David Robie
相关产品推荐
相关产品推荐

