我知道这可能是一个愚蠢的问题,但我很好奇是否有任何区别,我更喜欢使用 str_detect,因为语法在我的大脑中更有意义。
(我是新来的,所以我不知道是否需要为这样的问题输入代码?)
是的,存在很大差异。首先,
contains()
是一个“选择助手”,必须在(通常是tidyverse)选择函数中使用。
所以你不能这样做:
x <- c("Hello", "and", "welcome (example)")
tidyselect::contains("Hello", x)
或者您收到错误:
错误:!
必须在 selecting 函数中使用。contains()
鉴于:
stringr::str_detect(x, "Hello")
退货:
[1] TRUE FALSE FALSE
其次,
stringr::str_detect()
允许正则表达式,而tidyselect::contains
仅查找文字字符串。
举个例子
df <- data.frame(col1 = c("Hello", "and", "welcome (example)"))
df %>%
select(contains("1"))
# returns
# col1
# 1 Hello
# 2 and
# 3 welcome (example)
但是
df %>% select(contains("\\d"))
不返回任何内容(
\\d
是“任何数字”的R正则表达式)
最重要的是,
contains()
只能用在select语句中。
此外,正如
tidyselect::contains()
的文档中提到的:
[...]
:包含文字字符串。contains()
[...]
、starts_with()
和ends_with()
请勿使用正则表达式。 [...]contains()
[...] 对于
、starts_with()
和ends_with()
这是完全匹配。contains()
然而,在
stringr::str_detect
的文档中:
pattern :要寻找的模式。 默认解释是正则表达式。
str_detect()
可以用在任何类型的陈述中