R/generate_data.R
genFactor.Rd
Create factor variable from an existing (non-double) variable
genFactor(dtName, varname, labels = NULL, prefix = "f", replace = FALSE)
Data table with columns.
Name of field(s) to be converted.
Factor level labels. If not provided, the generated factor levels will be used as the labels. Can be a vector (if only one new factor or all factors have the same labels) or a list of character vectors of the same length as varname.
By default, the new field name will be a concatenation of "f" and the old field name. A prefix string can be provided.
If replace is set to TRUE (defaults to FALSE) the field referenced varname will be removed.
# First example:
def <- defData(varname = "cat", formula = ".2;.3;.5", dist = "categorical")
def <- defData(def, varname = "x", formula = 5, variance = 2)
dx <- genData(200, def)
dx
#> Key: <id>
#> id cat x
#> <int> <int> <num>
#> 1: 1 1 6.173198
#> 2: 2 3 3.451851
#> 3: 3 2 4.505016
#> 4: 4 3 6.589504
#> 5: 5 2 1.835221
#> ---
#> 196: 196 3 5.704497
#> 197: 197 1 4.854637
#> 198: 198 3 4.258349
#> 199: 199 3 4.017217
#> 200: 200 3 4.772752
dx <- genFactor(dx, "cat", labels = c("one", "two", "three"))
dx
#> Key: <id>
#> id cat x fcat
#> <int> <int> <num> <fctr>
#> 1: 1 1 6.173198 one
#> 2: 2 3 3.451851 three
#> 3: 3 2 4.505016 two
#> 4: 4 3 6.589504 three
#> 5: 5 2 1.835221 two
#> ---
#> 196: 196 3 5.704497 three
#> 197: 197 1 4.854637 one
#> 198: 198 3 4.258349 three
#> 199: 199 3 4.017217 three
#> 200: 200 3 4.772752 three
# Second example:
dx <- genData(10)
dx <- trtAssign(dtName = dx, 2, grpName = "studyArm")
dx <- genFactor(dx, varname = "studyArm", labels = c("control", "treatment"), prefix = "t_")
dx
#> Key: <id>
#> id studyArm t_studyArm
#> <int> <int> <fctr>
#> 1: 1 0 control
#> 2: 2 1 treatment
#> 3: 3 1 treatment
#> 4: 4 0 control
#> 5: 5 0 control
#> 6: 6 1 treatment
#> 7: 7 0 control
#> 8: 8 1 treatment
#> 9: 9 0 control
#> 10: 10 1 treatment