View source: R/bruceR-stats_1_basic.R
add | R Documentation |
Enhanced functions to create, modify, and/or delete variables.
The functions combine the advantages of
within
(base),
mutate
(dplyr),
transmute
(dplyr), and
:=
(data.table).
See examples below for the usage and convenience.
add(data, expr, when, by, drop = FALSE)
added(data, expr, when, by, drop = FALSE)
data |
A |
expr |
R expression(s) enclosed in Passing to Execute each line of expression in |
when |
[Optional] Compute for which rows or rows meeting what condition(s)? Passing to |
by |
[Optional] Compute by what group(s)? Passing to |
drop |
Drop existing variables and return only new variables?
Defaults to |
add()
returns a new
data.table
,
with the raw data unchanged.
added()
returns nothing and has already changed the raw data.
add()
: Return the new data.
You need to assign the new data to an object:
data = add(data, {...})
added()
: Return nothing and change the raw data immediately.
NO need to assign the new data:
added(data, {...})
## ====== Usage 1: add() ====== ##
d = as.data.table(within.1)
d$XYZ = 1:8
d
# add() does not change the raw data:
add(d, {B = 1; C = 2})
d
# new data should be assigned to an object:
d = d %>% add({
ID = str_extract(ID, "\\d") # modify a variable
XYZ = NULL # delete a variable
A = .mean("A", 1:4) # create a new variable
B = A * 4 # new variable is immediately available
C = 1 # never need ,/; at the end of any line
})
d
## ====== Usage 2: added() ====== ##
d = as.data.table(within.1)
d$XYZ = 1:8
d
# added() has already changed the raw data:
added(d, {B = 1; C = 2})
d
# raw data has already become the new data:
added(d, {
ID = str_extract(ID, "\\d")
XYZ = NULL
A = .mean("A", 1:4)
B = A * 4
C = 1
})
d
## ====== Using `when` and `by` ====== ##
d = as.data.table(between.2)
d
added(d, {SCORE2 = SCORE - mean(SCORE)},
A == 1 & B %in% 1:2, # `when`: for what conditions
by=B) # `by`: by what groups
d
na.omit(d)
## ====== Return Only New Variables ====== ##
newvars = add(within.1, {
ID = str_extract(ID, "\\d")
A = .mean("A", 1:4)
}, drop=TRUE)
newvars
## ====== Better Than `base::within()` ====== ##
d = as.data.table(within.1)
# wrong order: C B A
within(d, {
A = 4
B = A + 1
C = 6
})
# correct order: A B C
add(d, {
A = 4
B = A + 1
C = 6
})
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.