You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在switch语句中匹配字符串:按字符串前两位分支的实现问题

Solution: Using Switch with String Prefix Matching in R

The problem with your original code is that R's switch() function only does exact value matching—it doesn't interpret case labels as regular expressions. So when you use "^aa" as a case, it's looking for a string that's literally "^aa", not strings starting with "aa".

Here's how to fix this by first extracting the first two characters of your input string, then using switch() on that prefix (while still handling exact matches like "bbbb"):

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

foo <- Vectorize(function(a) {
  # Extract the first two characters of the string
  prefix <- substr(a, 1, 2)
  
  # First check for exact matches (like "bbbb")
  exact_match <- switch(a, "bbbb" = "Grape", NULL)
  
  if (!is.null(exact_match)) {
    # Return the exact match result if it exists
    exact_match
  } else {
    # Use switch on the prefix for partial matches
    switch(prefix, 
           "aa" = "Apple", 
           # Add other prefix cases here if needed
           "Unknown") # Default case
  }
}, "a")

# Test it out
foo(test)

When you run this, you'll get the desired output:

aabb  aacc  bbbb 
"Apple" "Apple"   "Grape"

How this works:

  1. Extract the prefix: substr(a, 1, 2) grabs the first two characters of each input string.
  2. Check exact matches first: We use switch() to look for exact matches (like "bbbb")—if found, we return that result immediately.
  3. Prefix-based switch: If no exact match exists, we use another switch() on the extracted prefix to handle partial matches (like "aa" leading to "Apple").
  4. Vectorization: The Vectorize() wrapper ensures the function works on entire vectors of strings, just like your original code.

If you have more prefixes to match, you can easily add them to the second switch() (e.g., "bb" = "Banana" for strings starting with "bb" that aren't exactly "bbbb").

内容的提问来源于stack exchange,提问作者Damian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:46:43