r - str_detect 与外部对象模式(以整洁的方式..)
问题描述
我想优化我的代码。
我正在str_detect
做很多选择,因为我想为我想选择的未来优化我的代码,根据外部定义的对象定义一个过滤器模式。我可以这样做,但我必须使用as.character()
. 是否有可能以整洁的方式进行?
演示该问题的工作示例。这是经典的方法,它有效
> tbl %>% mutate(twentys = case_when(
+ str_detect(fruit, "20") ~ T) )
# A tibble: 4 x 3
x fruit twentys
<int> <chr> <lgl>
1 1 apple 20 TRUE
2 2 banana 20 TRUE
3 3 pear 10 NA
4 4 pineapple 10 NA
这就是我想象的我可以做到的方式,但事实并非如此
> twenty <- 20
> tbl %>% mutate(twentys = case_when(
+ str_detect(fruit, twenty) ~ T) )
Error: Problem with `mutate()` input `twentys`.
x no applicable method for 'type' applied to an object of class "c('double', 'numeric')"
i Input `twentys` is `case_when(str_detect(fruit, twenty) ~ T)`.
Run `rlang::last_error()` to see where the error occurred.
as.character()
这是我想优化的繁琐方式,使用。
> tbl %>% mutate(twentys = case_when(
+ str_detect(fruit, as.character(twenty)) ~ T) )
# A tibble: 4 x 3
x fruit twentys
<int> <chr> <lgl>
1 1 apple 20 TRUE
2 2 banana 20 TRUE
3 3 pear 10 NA
4 4 pineapple 10 NA
解决方案
grepl
如果您不想转换twenty
为字符,则可以使用。
library(dplyr)
tbl %>% mutate(twentys = case_when(grepl(twenty, fruit) ~ TRUE))
# x fruit twentys
#1 1 apple 20 TRUE
#2 2 banana 20 TRUE
#3 3 pear 10 NA
#4 4 pineapple 10 NA
数据
tbl <- structure(list(x = 1:4, fruit = c("apple 20", "banana 20", "pear 10",
"pineapple 10")), class = "data.frame", row.names = c(NA, -4L))
twenty <- 20
推荐阅读
- python - 仅使用一次 onscreenclick
- reactjs - jest with typescript 在导入文件时抛出错误
- logging - 哪种最佳集中式日志记录方法适合实施和维护以管理 AWS ECS 上的容器?
- sql-server - 在 SSIS 中连接多个列
- ng2-smart-table - 是否可以在 ng2-smart-table 的列标题中添加工具提示
- python - 如何读取相对较大的 csv 文件?
- git - GitHub 通过 git 在服务器和本地 pc 之间
- javascript - 沃尔玛市场 OAuth API 不断抛出 SYSTEM_ERROR.GMP_GATEWAY_API 错误
- flutter - Flutter - 无法从 Cloud Firestore 中的数据生成变量 - 未定义名称错误
- java - Spring Boot 应用程序部署问题