使用 str_detect() 和 contains() 之间的区别?

问题描述 投票:0回答:2

我知道这可能是一个愚蠢的问题,但我很好奇是否有任何区别,我更喜欢使用 str_detect,因为语法在我的大脑中更有意义。

(我是新来的,所以我不知道是否需要为这样的问题输入代码?)

r stringr
2个回答
1
投票

是的,存在很大差异。首先,

contains()
是一个“选择助手”,必须在(通常是tidyverse)选择函数中使用。

所以你不能这样做:

x <- c("Hello", "and", "welcome (example)") 

tidyselect::contains("Hello", x)

或者您收到错误:

错误:!

contains()
必须在 selecting 函数中使用。

鉴于:

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正则表达式)


0
投票

最重要的是,

contains()
只能用在select语句中。

此外,正如

tidyselect::contains()
的文档中提到的:

[...]

contains()
:包含文字字符串。

[...]

starts_with()
ends_with()
contains()
请勿使用正则表达式。 [...]

[...] 对于

starts_with()
ends_with()
contains()
这是完全匹配

然而,在

stringr::str_detect
的文档中:

pattern :要寻找的模式。 默认解释是正则表达式

str_detect()
可以用在任何类型的陈述中

© www.soinside.com 2019 - 2024. All rights reserved.