Graphics Reference
In-Depth Information
In this example, we'll recode the categorical variable group into another categorical variable,
treatment . If the old value was "ctrl" , the new value will be "No" , and if the old value was
"trt1" or "trt2" , the new value will be "Yes" .
This can be done with the match() function:
pg <- PlantGrowth
oldvals <- c( "ctrl" , "trt1" , "trt2" )
newvals <- factor(c( "No" ,
"Yes" , "Yes" ))
pg$treatment <- newvals[ match(pg$group, oldvals) ]
It can also be done (more awkwardly) by indexing in the vectors:
pg$treatment[pg$group == "ctrl" ] <- "no"
pg$treatment[pg$group == "trt1" ] <- "yes"
pg$treatment[pg$group == "trt2" ] <- "yes"
# Convert to a factor
pg$treatment <- factor(pg$treatment)
pg
weight group treatment
4.17 ctrl no
5.58 ctrl no
4.81 trt1 yes
6.31 trt2 yes
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 Changing the Names of Factor Levels .
Discussion
The coding criteria can also be based on values in multiple columns, by using the & and | oper-
ators:
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
Search WWH ::




Custom Search