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
#> id cat x
#> 1: 1 3 3.914439
#> 2: 2 3 4.482196
#> 3: 3 3 2.031990
#> 4: 4 1 5.646096
#> 5: 5 2 3.280469
#> ---
#> 196: 196 3 4.031803
#> 197: 197 3 3.423400
#> 198: 198 2 5.876663
#> 199: 199 2 5.303516
#> 200: 200 2 6.232819
dx <- genFactor(dx, "cat", labels = c("one", "two", "three"))
dx
#> id cat x fcat
#> 1: 1 3 3.914439 three
#> 2: 2 3 4.482196 three
#> 3: 3 3 2.031990 three
#> 4: 4 1 5.646096 one
#> 5: 5 2 3.280469 two
#> ---
#> 196: 196 3 4.031803 three
#> 197: 197 3 3.423400 three
#> 198: 198 2 5.876663 two
#> 199: 199 2 5.303516 two
#> 200: 200 2 6.232819 two
# Second example:
dx <- genData(10)
dx <- trtAssign(dtName = dx, 2, grpName = "studyArm")
dx <- genFactor(dx, varname = "studyArm", labels = c("control", "treatment"), prefix = "t_")
dx
#> id studyArm t_studyArm
#> 1: 1 1 treatment
#> 2: 2 0 control
#> 3: 3 1 treatment
#> 4: 4 0 control
#> 5: 5 0 control
#> 6: 6 1 treatment
#> 7: 7 0 control
#> 8: 8 0 control
#> 9: 9 1 treatment
#> 10: 10 1 treatment