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

如何在R语言中用dplyr实现条件mutate?含教育变量计算场景

Calculating a Conditional New Variable with dplyr

Hey there! Your nested if_else approach to calculating newvariable works perfectly, but we can make this code way cleaner and easier to maintain using dplyr's case_when() function—it’s built specifically for handling multiple conditional logic cases like this.

First, let’s confirm your logic to make sure we’re aligned:

  • If P46A is -98 or -99, set newvariable to NA
  • If P46A is 0 or 1, use the raw value of P47
  • If P46A falls between 2 and 4, calculate P47 + 3
  • If P46A is 5, 6, 7, or 11, calculate P47 + 16
  • If P46A is 8 or 9, calculate P47 + 23
  • For all other values of P46A, calculate P47 + 26

Here’s the optimized code using case_when():

library(dplyr)

Datos <- Datos %>%
  mutate(newvariable = case_when(
    P46A %in% c(-98, -99) ~ NA_real_,
    P46A %in% c(0, 1) ~ P47,
    P46A %in% 2:4 ~ P47 + 3,
    P46A %in% c(5:7, 11) ~ P47 + 16,
    P46A %in% c(8, 9) ~ P47 + 23,
    TRUE ~ P47 + 26  # Catch-all for any unlisted P46A values
  ))

Why this is better than nested if_else:

  • Readability: Each condition and its corresponding calculation sits on its own line, so you can quickly scan and verify the rules without digging through nested brackets.
  • Maintainability: If you need to adjust any rule later (like adding a new P46A category), you just edit the relevant line instead of reworking nested logic.
  • Consistency: case_when() evaluates conditions in top-to-bottom order, just like your original nested if_else calls—so the output will be identical to your initial code.

A quick note: We use NA_real_ instead of plain NA here to avoid potential type mismatches, since P47 is likely a numeric variable.

内容的提问来源于stack exchange,提问作者Cristian Camilo Hidalgo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:17:01