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
#> Key: <id>
#> id cat x
#> <int> <int> <num>
#> 1: 1 1 5.386162
#> 2: 2 1 4.000863
#> 3: 3 3 2.969063
#> 4: 4 1 6.150931
#> 5: 5 1 4.169393
#> ---
#> 196: 196 2 4.680767
#> 197: 197 3 2.975392
#> 198: 198 2 6.246475
#> 199: 199 3 7.503776
#> 200: 200 2 5.630722
dx <- genFactor(dx, "cat", labels = c("one", "two", "three"), replace = TRUE)
dx <- genDummy(dx, varname = "fcat", sep = "_")
dx
#> Key: <id>
#> id x fcat fcat_one fcat_two fcat_three
#> <int> <num> <fctr> <int> <int> <int>
#> 1: 1 5.386162 one 1 0 0
#> 2: 2 4.000863 one 1 0 0
#> 3: 3 2.969063 three 0 0 1
#> 4: 4 6.150931 one 1 0 0
#> 5: 5 4.169393 one 1 0 0
#> ---
#> 196: 196 4.680767 two 0 1 0
#> 197: 197 2.975392 three 0 0 1
#> 198: 198 6.246475 two 0 1 0
#> 199: 199 7.503776 three 0 0 1
#> 200: 200 5.630722 two 0 1 0
# Second example:
dx <- genData(15)
dx <- trtAssign(dtName = dx, 3, grpName = "arm")
dx <- genDummy(dx, varname = "arm")
dx
#> Key: <id>
#> id arm arm.1 arm.2 arm.3
#> <int> <int> <int> <int> <int>
#> 1: 1 2 0 1 0
#> 2: 2 3 0 0 1
#> 3: 3 3 0 0 1
#> 4: 4 1 1 0 0
#> 5: 5 3 0 0 1
#> 6: 6 2 0 1 0
#> 7: 7 3 0 0 1
#> 8: 8 2 0 1 0
#> 9: 9 1 1 0 0
#> 10: 10 3 0 0 1
#> 11: 11 1 1 0 0
#> 12: 12 1 1 0 0
#> 13: 13 2 0 1 0
#> 14: 14 2 0 1 0
#> 15: 15 1 1 0 0