关注 startsWith 和 R 中的多种模式

Concern with startsWith and multiple patterns in R

我注意到 startsWith() 函数存在问题或疑虑。 以下代码显示两个不同的选择。 第一个行为正常,就是这段代码:

dt_test <- data.table(a = c("abcd", "poo", "abla", "ba"),
                      id = c(1,2,3, 4))

dt_test[startsWith(a, c("ab", "ao")),id]
# [1] 1 3

startsWith(dt_test$a, c("ab", "ao"))
# TRUE FALSE TRUE FALSE

如果你注意到了,这个只选择了第一个,这是违反直觉的,因为 id 2 和 4 应该是 TRUE

dt_test <- data.table(a = c("ab","abcd", "poo", "abla", "ba"),
                      id = c(1,2,3, 4,5))

dt_test[startsWith(a, c("ab", "ao")),id]
# [1] 1

startsWith(dt_test$a, c("ab", "ao"))
# [1]  TRUE FALSE FALSE FALSE FALSE

在这种情况下,我应该用什么来代替 startsWith()

我们需要传递多个 startsWith

library(data.table)
dt_test[Reduce(`|`, lapply(c('ab', 'ao'), startsWith, x = a))]
#     a id
#1:   ab  1
#2: abcd  2
#3: abla  4

或者直接使用grepl

dt_test[grepl('^a[bo]', a)]
#      a id
#1:   ab  1
#2: abcd  2
#3: abla  4

%like%

dt_test[a %like% '^a[bo]']
#      a id
#1:   ab  1
#2: abcd  2
#3: abla  4

?startsWith() 帮助页面显示

prefix, suffix: character vector (often of length one).

在您的情况下,您传递的字符不止一个。因此,startsWith内不允许有多个模式。

你可以试试这个:

dt_test[grepl('^ab|^ao', a)]