gpt4 book ai didi

r - 匹配 switch 语句中的字符串

转载 作者:行者123 更新时间:2023-12-02 08:07:44 25 4
gpt4 key购买 nike

我想使用switch 语句根据字符串的前两个字符进行分支。在下面显示的示例中,我想返回带有“aabb”或“aacc”的“Apple”

test<-c("aabb", "aacc", "bbbb")

foo <- Vectorize(function(a) {
switch(as.character(a),
"^aa" = "Apple",
"bbbb" = "Grape",
"Unknown")

}, "a")

> foo(test)
aabb aacc bbbb
"Unknown" "Unknown" "Grape"

如果存在完全匹配,我可以使该语句起作用,但我不知道如何仅使用前两个字符来获得匹配。也许有一种使用正则表达式的方法?如图所示,我尝试使用 ^ 来匹配字符串的开头(与 grep 一起使用)但它不起作用。

我想我可以在 grepl 中使用嵌套的 ifelse 语句,但是它可以使用 switch 吗?

最佳答案

根据手册,这对于 switch 是不可能的,因为它只允许完全匹配:

switch(EXPR, ...)

If EXPR evaluates to a character string then that string is matched (exactly) to the names of the elements in ....

但是你可以在 dplyr 中使用 case_when 来完成:

foo <- function(x){
dplyr::case_when(
grepl('^aa', x) ~ 'Apple',
x == 'bbbb' ~ 'Grape',
TRUE ~ 'Unknown'
)
}
foo(test)
# [1] "Apple" "Apple" "Grape"

关于r - 匹配 switch 语句中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49961821/

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