Concern with startsWith and multiple patterns in R

时光怂恿深爱的人放手 提交于 2021-02-05 06:27:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!