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
#> Key: <id>
#>         id   cat        x
#>      <int> <int>    <num>
#>   1:     1     3 6.423834
#>   2:     2     3 5.942421
#>   3:     3     3 6.754430
#>   4:     4     1 3.533844
#>   5:     5     3 2.531178
#>  ---                     
#> 196:   196     2 5.084109
#> 197:   197     2 4.600363
#> 198:   198     2 4.521599
#> 199:   199     2 1.991064
#> 200:   200     1 5.998426

dx <- genFactor(dx, "cat", labels = c("one", "two", "three"))
dx
#> Key: <id>
#>         id   cat        x   fcat
#>      <int> <int>    <num> <fctr>
#>   1:     1     3 6.423834  three
#>   2:     2     3 5.942421  three
#>   3:     3     3 6.754430  three
#>   4:     4     1 3.533844    one
#>   5:     5     3 2.531178  three
#>  ---                            
#> 196:   196     2 5.084109    two
#> 197:   197     2 4.600363    two
#> 198:   198     2 4.521599    two
#> 199:   199     2 1.991064    two
#> 200:   200     1 5.998426    one

# 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        1  treatment
#>  5:     5        1  treatment
#>  6:     6        0    control
#>  7:     7        0    control
#>  8:     8        0    control
#>  9:     9        1  treatment
#> 10:    10        0    control