在switch语句中匹配字符串:按字符串前两位分支的实现问题
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:
- Extract the prefix:
substr(a, 1, 2)grabs the first two characters of each input string. - Check exact matches first: We use
switch()to look for exact matches (like"bbbb")—if found, we return that result immediately. - 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"). - 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

