Chapter 7 Convert to a factor

pg\(treatment <- factor(pg\)treatment) pg #> weight group treatment #> 1 4.17 ctrl No #> 2 5.58 ctrl No #> 11 4.81 trt1 Yes #> 21 6.31 trt2 Yes #> 22 5.12 trt2 Yes


Here, we combined two of the factor levels and put the result into a new column. If you simply want to rename the levels of a factor, see Recipe \@ref(RECIPE-DATAPREP-FACTOR-RENAME).

The coding criteria can also be based on values in multiple columns, by using the `&` and `|` operators:




```r
pg$newcol[pg$group == "ctrl" & pg$weight < 5]  <- "no_small"
pg$newcol[pg$group == "ctrl" & pg$weight >= 5] <- "no_large"
pg$newcol[pg$group == "trt1"] <- "yes"
pg$newcol[pg$group == "trt2"] <- "yes"
pg$newcol <- factor(pg$newcol)
pg
#>    weight group   newcol
#> 1    4.17  ctrl no_small
#> 2    5.58  ctrl no_large
#> 11   4.81  trt1      yes
#> 21   6.31  trt2      yes
#> 22   5.12  trt2      yes

It’s also possible to combine two columns into one using the interaction() function, which appends the values with a . in between. This combines the weight and group columns into a new column, weightgroup:

pg$weightgroup <- interaction(pg$weight, pg$group)
pg
#>    weight group weightgroup
#> 1    4.17  ctrl   4.17.ctrl
#> 2    5.58  ctrl   5.58.ctrl
#> 11   4.81  trt1   4.81.trt1
#> 21   6.31  trt2   6.31.trt2
#> 22   5.12  trt2   5.12.trt2

7.0.1 See Also

For more on renaming factor levels, see Recipe ??.

See Recipe 7.1 for recoding continuous values to categorical values.