Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

Concern with startsWith and multiple patterns in R

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?

question from:https://stackoverflow.com/questions/65836695/mutate-a-new-column-using-dplyr-with-values-based-on-multiple-conditions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...