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.934799
#> 2: 2 3 3.821661
#> 3: 3 2 7.517916
#> 4: 4 1 5.965938
#> 5: 5 3 6.376257
#> ---
#> 196: 196 2 2.999271
#> 197: 197 3 4.462641
#> 198: 198 3 4.012578
#> 199: 199 1 5.984149
#> 200: 200 1 4.242661
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.934799 one 1 0 0
#> 2: 2 3.821661 three 0 0 1
#> 3: 3 7.517916 two 0 1 0
#> 4: 4 5.965938 one 1 0 0
#> 5: 5 6.376257 three 0 0 1
#> ---
#> 196: 196 2.999271 two 0 1 0
#> 197: 197 4.462641 three 0 0 1
#> 198: 198 4.012578 three 0 0 1
#> 199: 199 5.984149 one 1 0 0
#> 200: 200 4.242661 one 1 0 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 2 0 1 0
#> 3: 3 1 1 0 0
#> 4: 4 3 0 0 1
#> 5: 5 1 1 0 0
#> 6: 6 3 0 0 1
#> 7: 7 2 0 1 0
#> 8: 8 2 0 1 0
#> 9: 9 3 0 0 1
#> 10: 10 1 1 0 0
#> 11: 11 1 1 0 0
#> 12: 12 2 0 1 0
#> 13: 13 3 0 0 1
#> 14: 14 3 0 0 1
#> 15: 15 1 1 0 0