varcalc_dt | R Documentation |
This assumes a *long* format with a single value column, dcasts the data.table to wide format, executes the calulation(s), melts back to long format and returns the resulting data.table with the additional column(s).
varcalc_dt(dt, varcol, valcol, expr, ...)
dt |
data.table, long format |
varcol |
name of the column with the variable |
valcol |
name of the column with the value |
expr |
vector of expressions to be handed to j in data.table, as strings, e.g., "a := b/c" |
... |
other arguments are passed on to the data.table call where 'expr' is evaluated. Most likely you want to pass the 'by=' parameter for group-by calls, see examples. |
Note that the data.table should have at least three columns, i.e., the variable, the value and one id column.
mt_dt <- as.data.table(mtcars, keep.rownames = TRUE)
## to long
mt1 <- melt(mt_dt, id.vars=c("rn", "cyl"))
varcalc_dt(mt1, "variable", "value", c("`spec. hp` := wt/hp", "wsum := sum(wt)"), by="cyl")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.