我试图使用dplyr
从data.frame
中删除列,其中列名包含除名称开头以外的任何子字符串(即除第一个索引外的任何索引).
环顾四周(双关语),这似乎通常是通过在dplyr::select()
调用中传递给dplyr::matches()
的正则表达式中包含lookbehind断言来实现的.我不熟悉这些是如何工作的,但我在下面try 实现这一点时出现了一个错误.
我是否错误地实现了lookbehind,或者这是我可以传递到matches()
的正则表达式的限制?我欢迎一个有效的解决方案.
library(dplyr)
# Example data
df <- data.frame(bar = rnorm(1),
foo1 = rnorm(1),
bar_foo1 = rnorm(1),
bar_foo1_bat = rnorm(1))
# Desired output
df %>% select(bar, foo1)
#> bar foo1
#> 1 1.057651 -0.1526598
# Sucessfully drops columns with "foo1" anywhere
df %>% select(-matches(".*foo1.*"))
#> bar
#> 1 1.057651
# Both fail to drop columns with "foo1" anywhere *except the start of the string*
df %>% select(-matches("(?<!^).*foo1.*"))
#> Warning in grep(needle, haystack, ...): TRE pattern compilation error 'Invalid
#> regexp'
#> Error in `select()`:
#> ! invalid regular expression '(?<!^).*foo1.*', reason 'Invalid regexp'
df %>% select(-matches("(?<!^)foo1.*"))
#> Warning in grep(needle, haystack, ...): TRE pattern compilation error 'Invalid
#> regexp'
#> Error in `select()`:
#> ! invalid regular expression '(?<!^)foo1.*', reason 'Invalid regexp'
由reprex package(v2.0.1)于2022-07-14创建