如何在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
P46Ais-98or-99, setnewvariabletoNA - If
P46Ais0or1, use the raw value ofP47 - If
P46Afalls between2and4, calculateP47 + 3 - If
P46Ais5,6,7, or11, calculateP47 + 16 - If
P46Ais8or9, calculateP47 + 23 - For all other values of
P46A, calculateP47 + 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
P46Acategory), 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 nestedif_elsecalls—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
相关产品推荐
相关产品推荐

