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( # detect rows with both a and b set testexpr = qe((a+b)>1), thenexprs = c( if_else_device( # randomly clear one of a or b testexpr = qe(runif(dplyr::n()) >= 0.5), thenexprs = qae(a := 0), elseexprs = qae(b := 0)), qae(edited := TRUE))) print(program)
#> ifebtest_u7fd78yvg5fi #> "(a + b) > 1" #> ifebtest_wl4dieexombe #> "runif(dplyr::n()) >= 0.5" #> a #> "ifelse( ifebtest_u7fd78yvg5fi, ifelse( ifebtest_wl4dieexombe, 0, a), a)" #> b #> "ifelse( ifebtest_u7fd78yvg5fi, ifelse( !( ifebtest_wl4dieexombe ), 0, b), b)" #> edited #> "ifelse( ifebtest_u7fd78yvg5fi, TRUE, edited)"
plan <- partition_mutate_se(program) print(plan)
#> $group00001 #> ifebtest_u7fd78yvg5fi ifebtest_wl4dieexombe #> "(a + b) > 1" "runif(dplyr::n()) >= 0.5" #> #> $group00002 #> a #> "ifelse( ifebtest_u7fd78yvg5fi, ifelse( ifebtest_wl4dieexombe, 0, a), a)" #> b #> "ifelse( ifebtest_u7fd78yvg5fi, ifelse( !( ifebtest_wl4dieexombe ), 0, b), b)" #> edited #> "ifelse( ifebtest_u7fd78yvg5fi, 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 1 0 TRUE #> 7 1 0 TRUE #> 8 1 0 TRUE #> 9 1 0 TRUE #> 10 0 1 TRUE