问题
I noticed a problem or a concern with the startsWith()
function.
The following code displays two different selection.
The first one behave normally which is this chunk of code:
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
And if you noticed, this one only selects the first one which is counter intuitive since id
2 and 4 are supposed to be 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
What I'm I supposed to use as a substitute to startsWith()
in this precise case?
回答1:
We need to pass either multiple 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
or simply use grepl
dt_test[grepl('^a[bo]', a)]
# a id
#1: ab 1
#2: abcd 2
#3: abla 4
Or with %like%
dt_test[a %like% '^a[bo]']
# a id
#1: ab 1
#2: abcd 2
#3: abla 4
回答2:
The ?startsWith()
help page indicates
prefix, suffix: character vector (often of length one).
In your case, you are passing more than one character. Therefore, multiple patterns are not allowed within startsWith
.
You may try this:
dt_test[grepl('^ab|^ao', a)]
来源:https://stackoverflow.com/questions/61088740/concern-with-startswith-and-multiple-patterns-in-r