View source: R/if_else_block.R
if_else_block | R Documentation |
if(){}else{}
.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. These expressions can then
be optimized into a minimal number of no-dependency
blocks by extend_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.frame
s or at a big data scale using
RPostgreSQL
or sparklyr
.
if_else_block(testexpr, ..., thenexprs = NULL, elseexprs = NULL)
testexpr |
character containing the test expression. |
... |
force later arguments to bind by name. |
thenexprs |
named character then assignments (altering columns, not creating). |
elseexprs |
named character else assignments (altering columns, not creating). |
Note: ifebtest_*
is a reserved column name for this procedure.
sequence of statements for extend_se().
if_else_op
if (requireNamespace("DBI", quietly = TRUE) && requireNamespace("RSQLite", quietly = TRUE)) {
# Example: clear one of a or b in any row where both are set.
# Land random selections early to avoid SQLite bug.
my_db <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
d <- rq_copy_to(
my_db,
'd',
data.frame(i = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
a = c(0, 0, 1, 1, 1, 1, 1, 1, 1, 1),
b = c(0, 1, 0, 1, 1, 1, 1, 1, 1, 1),
r = runif(10),
edited = 0),
temporary=TRUE, overwrite=TRUE)
program <- if_else_block(
testexpr = qe((a+b)>1),
thenexprs = c(
if_else_block(
testexpr = qe(r >= 0.5),
thenexprs = qae(a %:=% 0),
elseexprs = qae(b %:=% 0)),
qae(edited %:=% 1)))
print(program)
optree <- extend_se(d, program)
cat(format(optree))
sql <- to_sql(optree, my_db)
cat(sql)
print(DBI::dbGetQuery(my_db, sql))
# Why we need to land the random selection early
# for SQLIte:
q <- "SELECT r AS r1, r AS r2 FROM (
SELECT random() AS r FROM (
SELECT * from ( VALUES(1),(2) )
) a
) b"
print(DBI::dbGetQuery(my_db, q))
DBI::dbDisconnect(my_db)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.