首页 > 解决方案 > 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     

标签: rpattern-matchingtidyverse

解决方案


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

推荐阅读