if_else_device: Simulate a per-row block-'if(){}else{}'.

Description Usage Arguments Details Examples

View source: R/stmtPlanner.R

Description

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.

Usage

1
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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)

plan <- partition_mutate_se(program)
print(plan)

res <- d %.>%
  mutate_seb(., plan) %.>%
  select_se(., grepdf('^ifebtest_.*', ., invert=TRUE))
print(res)

seplyr documentation built on Sept. 5, 2021, 5:12 p.m.