R语言case_when函数中使用表达式而非算术运算的问题
Got it, let's fix this case_when() issue for you! The main problems in your code are likely mixing base R-style subsetting with dplyr's tidy evaluation and not properly structuring your column creation step. Here's how to get it working correctly:
Step 1: Set up your data and load dplyr
First, confirm your data frame and load the required package:
library(dplyr) my_df <- data.frame(H = c("ABC", "DEF", "GHI"))
Step 2: Correct case_when() usage with mutate()
Instead of trying to assign to output_df$D directly (which assumes output_df already exists), use dplyr's mutate() to create the new column in a pipeline. Also, you don't need to use my_df$ inside case_when()—dpplyr automatically references columns from the data frame being processed:
output_df <- my_df %>% mutate(D = case_when( H == "ABC" ~ substr(H, 1, 3), # Keep full string for ABC H == "DEF" ~ substr(H, 1, 2), # First 2 chars for DEF TRUE ~ substr(H, 1, 1) # Catch-all: first char for everything else ))
Why this works:
- The pipe (
%>%) passesmy_dfintomutate(), so we can reference columnHdirectly without prefixing it. case_when()evaluates each condition in order: the first matching condition's right-hand expression is used.- The
TRUE ~ ...line acts as a default for any values that don't match the earlier conditions (I filled it withsubstr(H,1,1)—adjust this to your actual default logic!).
Result
Running the code above will give you:
H D 1 ABC ABC 2 DEF DE 3 GHI G
Key tip: Ensure all right-hand side expressions return the same data type (all character strings here, which is consistent). If you mix types (e.g., a string and a number), case_when() will throw an error.
内容的提问来源于stack exchange,提问作者ANmike

