Create dummy variables from a factor or integer variable
genDummy(dtName, varname, sep = ".", replace = FALSE)
Data table with column
Name of factor
Character to be used in creating new name for dummy fields. Valid characters include all letters and "_". Will default to ".". If an invalid character is provided, it will be replaced by default.
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 4.479586
#> 2: 2 1 5.234123
#> 3: 3 2 4.100791
#> 4: 4 3 6.225520
#> 5: 5 2 6.188477
#> ---
#> 196: 196 3 6.966713
#> 197: 197 3 4.144871
#> 198: 198 3 6.773981
#> 199: 199 2 2.501137
#> 200: 200 3 3.028021
dx <- genFactor(dx, "cat", labels = c("one", "two", "three"), replace = TRUE)
dx <- genDummy(dx, varname = "fcat", sep = "_")
dx
#> id x fcat fcat_one fcat_two fcat_three
#> 1: 1 4.479586 three 0 0 1
#> 2: 2 5.234123 one 1 0 0
#> 3: 3 4.100791 two 0 1 0
#> 4: 4 6.225520 three 0 0 1
#> 5: 5 6.188477 two 0 1 0
#> ---
#> 196: 196 6.966713 three 0 0 1
#> 197: 197 4.144871 three 0 0 1
#> 198: 198 6.773981 three 0 0 1
#> 199: 199 2.501137 two 0 1 0
#> 200: 200 3.028021 three 0 0 1
# Second example:
dx <- genData(15)
dx <- trtAssign(dtName = dx, 3, grpName = "arm")
dx <- genDummy(dx, varname = "arm")
dx
#> id arm arm.1 arm.2 arm.3
#> 1: 1 2 0 1 0
#> 2: 2 3 0 0 1
#> 3: 3 1 1 0 0
#> 4: 4 1 1 0 0
#> 5: 5 2 0 1 0
#> 6: 6 1 1 0 0
#> 7: 7 2 0 1 0
#> 8: 8 2 0 1 0
#> 9: 9 2 0 1 0
#> 10: 10 3 0 0 1
#> 11: 11 3 0 0 1
#> 12: 12 3 0 0 1
#> 13: 13 1 1 0 0
#> 14: 14 1 1 0 0
#> 15: 15 3 0 0 1