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

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 (%>%) passes my_df into mutate(), so we can reference column H directly 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 with substr(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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:55:34