gpt4 book ai didi

r - 在 dplyr select 中使用 perl=TRUE regex

转载 作者:行者123 更新时间:2023-12-04 13:56:52 25 4
gpt4 key购买 nike

如何使用 perl = TRUE 选择列像正则表达式。

data.frame(baa=0,boo=0,boa=0,lol=0,bAa=0) %>% dplyr::select(matches("(?i)b(?!a)"))

Error in grep(needle, haystack, ...) : invalid regular expression '(?i)b(?!a)', reason 'Invalid regexp'



正则表达式确实有效。
grep("(?i)b(?!a)",c("baa","boo","boa","lol","bAa"),perl=T)

> [1] 2 3

有快捷功能/方式吗?

最佳答案

matchesdplyr不支持perl = TRUE .但是,您可以创建自己的函数。在对源代码进行一些挖掘之后,这有效:

快捷方式:

library(dplyr)

#notice the 3 colons because grep_vars is not exported from dplyr
matches2 <- function (match, ignore.case = TRUE, vars = current_vars())
{
dplyr:::grep_vars(match, vars, ignore.case = ignore.case, perl = TRUE)
}

data.frame(baa=0,boo=0,boa=0,lol=0,bAa=0) %>% select(matches2("(?i)b(?!a)"))
#boo boa
#1 0 0

或者更解释性的解决方案:
matches2 <- function (match, ignore.case = TRUE, vars = current_vars()) 
{
grep_vars2(match, vars, ignore.case = ignore.case)
}

#this is pretty much my only change in the original dplyr:::grep_vars
#to make it accept perl.
grep_vars2 <- function (needle, haystack, ...)
{
grep(needle, haystack, perl = TRUE, ...)
}

data.frame(baa=0,boo=0,boa=0,lol=0,bAa=0) %>%
select(matches2("(?i)b(?!a)"))
#boo boa
#1 0 0

关于r - 在 dplyr select 中使用 perl=TRUE regex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47889573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com