R语言dplyr使用where()按变量标签筛选列的报错如何解决?
报错原因
- 内置
mtcars数据集默认没有为列设置label属性,调用attributes(.)$label会返回NULL - 即便数据集存在带标签的列,未设置标签的列也会返回
NULL,str_detect处理NULL时返回长度为0的逻辑值,不符合where()要求的逐列返回单个布尔值的规则
修复代码
增加NULL判断逻辑,无标签的列直接返回FALSE跳过,有标签的列再执行匹配:
library(dplyr) library(stringr) mtcars %>% select(where(~ { col_label <- attributes(.)$label !is.null(col_label) && str_detect(col_label, 'Miles') }))
效果测试
可以先为mtcars的mpg列添加标签验证效果:
# 给mpg列添加测试标签 attr(mtcars$mpg, "label") <- "Miles Per Gallon" # 执行筛选代码,会正常返回匹配到的mpg列 mtcars %>% select(where(~ { col_label <- attributes(.)$label !is.null(col_label) && str_detect(col_label, 'Miles') }))
内容的提问来源于stack exchange,提问作者nicholas
相关产品推荐
相关产品推荐

