Create factor variable from an existing (non-double) variable

genFactor(dtName, varname, labels = NULL, prefix = "f", replace = FALSE)

Arguments

dtName

Data table with columns.

varname

Name of field(s) to be converted.

labels

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.

prefix

By default, the new field name will be a concatenation of "f" and the old field name. A prefix string can be provided.

replace

If replace is set to TRUE (defaults to FALSE) the field referenced varname will be removed.

Examples

# 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 6.3663010 #> 2: 2 3 5.7637293 #> 3: 3 3 3.7086410 #> 4: 4 3 4.4492798 #> 5: 5 3 5.4322666 #> --- #> 196: 196 3 4.3121550 #> 197: 197 3 3.5968250 #> 198: 198 2 1.6055998 #> 199: 199 3 0.2882947 #> 200: 200 3 5.7856142
dx <- genFactor(dx, "cat", labels = c("one", "two", "three")) dx
#> id cat x fcat #> 1: 1 3 6.3663010 three #> 2: 2 3 5.7637293 three #> 3: 3 3 3.7086410 three #> 4: 4 3 4.4492798 three #> 5: 5 3 5.4322666 three #> --- #> 196: 196 3 4.3121550 three #> 197: 197 3 3.5968250 three #> 198: 198 2 1.6055998 two #> 199: 199 3 0.2882947 three #> 200: 200 3 5.7856142 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
#> id studyArm t_studyArm #> 1: 1 0 control #> 2: 2 0 control #> 3: 3 0 control #> 4: 4 1 treatment #> 5: 5 1 treatment #> 6: 6 1 treatment #> 7: 7 0 control #> 8: 8 1 treatment #> 9: 9 1 treatment #> 10: 10 0 control