This device uses expression-ifelse(,,) to simulate the more powerful per-row block-if(){}else{}. The difference is expression-ifelse(,,) can choose per-row what value to express, whereas block-if(){}else{} can choose per-row where to assign multiple values. By simulation we mean: a sequence of quoted mutate expressions are emitted that implement the transform (versus a using a custom dplyr pipe stage or function). These expressions can then be optimized into a minimal number of no-dependency blocks by partition_mutate_se for efficient execution. The idea is the user can write legible code in this notation, and the translation turns it into safe and efficient code suitable for execution either on data.frames or at a big data scale using RPostgreSQL or sparklyr.

if_else_device(testexpr, thenexprs = NULL, elseexprs = NULL)

Arguments

testexpr

character containing the test expression.

thenexprs

named character then assignments (altering columns, not creating).

elseexprs

named character else assignments (altering columns, not creating).

Details

Note: ifebtest_* is a reserved column name for this procedure.

Examples

# Example: clear one of a or b in any row where both are set. d <- data.frame(a = c(0, 0, 1, 1, 1, 1, 1, 1, 1, 1), b = c(0, 1, 0, 1, 1, 1, 1, 1, 1, 1), edited = FALSE) program <- if_else_device( testexpr = '(a+b)>1', thenexprs = c( if_else_device( testexpr = 'runif(n()) >= 0.5', thenexprs = 'a' := '0', elseexprs = 'b' := '0'), 'edited' := 'TRUE')) print(program)
#> ifebtest_blohocn9ky0h #> "(a+b)>1" #> ifebtest_c4vfaqrk015g #> "runif(n()) >= 0.5" #> a #> "ifelse( ifebtest_blohocn9ky0h, ifelse( ifebtest_c4vfaqrk015g, 0, a), a)" #> b #> "ifelse( ifebtest_blohocn9ky0h, ifelse( !( ifebtest_c4vfaqrk015g ), 0, b), b)" #> edited #> "ifelse( ifebtest_blohocn9ky0h, TRUE, edited)"
plan <- partition_mutate_se(program) print(plan)
#> $group00001 #> ifebtest_blohocn9ky0h ifebtest_c4vfaqrk015g #> "(a+b)>1" "runif(n()) >= 0.5" #> #> $group00002 #> a #> "ifelse( ifebtest_blohocn9ky0h, ifelse( ifebtest_c4vfaqrk015g, 0, a), a)" #> b #> "ifelse( ifebtest_blohocn9ky0h, ifelse( !( ifebtest_c4vfaqrk015g ), 0, b), b)" #> edited #> "ifelse( ifebtest_blohocn9ky0h, TRUE, edited)" #>
res <- d %.>% mutate_seb(., plan) %.>% select_se(., grepdf('^ifebtest_.*', ., invert=TRUE)) print(res)
#> a b edited #> 1 0 0 FALSE #> 2 0 1 FALSE #> 3 1 0 FALSE #> 4 0 1 TRUE #> 5 0 1 TRUE #> 6 0 1 TRUE #> 7 1 0 TRUE #> 8 1 0 TRUE #> 9 1 0 TRUE #> 10 0 1 TRUE
## Note: with wrapr version 1.0.2 or greater ## you can write this without quotes code as: # program <- if_else_device( # testexpr = qe((a+b)>1), # thenexprs = c( # if_else_device( # testexpr = qe(runif(n()) >= 0.5), # thenexprs = qae(a := 0), # elseexprs = qae(b := 0)), # qae(edited := TRUE)))