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     1 1.978686
#>   2:     2     3 4.636803
#>   3:     3     2 5.128509
#>   4:     4     1 9.050061
#>   5:     5     1 3.772308
#>  ---                     
#> 196:   196     3 3.306819
#> 197:   197     2 1.924692
#> 198:   198     3 5.384515
#> 199:   199     3 3.646255
#> 200:   200     1 3.181473

dx <- genFactor(dx, "cat", labels = c("one", "two", "three"))
dx
#> Key: <id>
#>         id   cat        x   fcat
#>      <int> <int>    <num> <fctr>
#>   1:     1     1 1.978686    one
#>   2:     2     3 4.636803  three
#>   3:     3     2 5.128509    two
#>   4:     4     1 9.050061    one
#>   5:     5     1 3.772308    one
#>  ---                            
#> 196:   196     3 3.306819  three
#> 197:   197     2 1.924692    two
#> 198:   198     3 5.384515  three
#> 199:   199     3 3.646255  three
#> 200:   200     1 3.181473    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        1  treatment
#>  2:     2        1  treatment
#>  3:     3        1  treatment
#>  4:     4        0    control
#>  5:     5        0    control
#>  6:     6        0    control
#>  7:     7        0    control
#>  8:     8        0    control
#>  9:     9        1  treatment
#> 10:    10        1  treatment