Description Usage Arguments Value Details Examples
View source: R/OutputDatabase_DataAccess.R
Add new field(s) to a table in dbOutput that is/are based on a calculation of values from (an) existing field(s)
1 2 3 4 5 6 7 8 9 10 11  | dbOutput_add_calculated_field(
  dbOut_fname,
  table,
  vars_orig,
  vars_new,
  FUN,
  ...,
  overwrite = FALSE,
  verbose = FALSE,
  chunk_size = 1e+05
)
 | 
dbOut_fname | 
 A character string. The path to the output database.  | 
table | 
 A character string. The table name to which the new field(s) should be appended.  | 
vars_orig | 
 A vector of character strings. The existing field names
that are used by   | 
vars_new | 
 A vector of character strings. The names of new fields.
The number must match the number of columns returned by   | 
FUN | 
 A function. See details.  | 
... | 
 Additional named arguments to   | 
overwrite | 
 A logical value. If   | 
verbose | 
 A logical value.  | 
chunk_size | 
 An integer value.  | 
The function is called for its side-effects on dbOut_fname.
The first argument of FUN must be a two-dimensional
object. This object contains the extracted values from dbOut_fname,
i.e., it has up to chunk_size rows and the columns are
vars_orig. Additional arguments can be passed via ....
The function must return a value (or values) corresponding to
vars_new for each row. These values are inserted into the new
field(s).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  | if (requireNamespace("RSQLite")) {
# Prepare database
dbOut_tmp <- tempfile(fileext = ".sqlite")
con <- RSQLite::dbConnect(RSQLite::SQLite(), dbOut_tmp)
data(iris)
x <- data.frame(P_id = seq_len(nrow(iris)), iris)
RSQLite::dbWriteTable(con, "iris", x)
RSQLite::dbDisconnect(con)
# Define calculation function
vars_orig <- c("Sepal.Length", "Sepal.Width")
example_calc <- function(x, delta = 1, ...) {
  apply(x, MARGIN = 1, function(x) delta * prod(x))
}
# Create new field based on a calculation
dbOutput_add_calculated_field(
  dbOut_fname = dbOut_tmp,
  table = "iris",
  vars_orig = vars_orig,
  vars_new = "calc",
  FUN = example_calc, delta = 2)
# Check the new field
con <- RSQLite::dbConnect(RSQLite::SQLite(), dbOut_tmp)
xout <- RSQLite::dbReadTable(con, "iris")
RSQLite::dbDisconnect(con)
res2 <- example_calc(x[, vars_orig], delta = 2)
all.equal(xout[, "calc"], res2)
# Cleanup
unlink(dbOut_tmp)
}
 | 
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.