I would like to create a set of dummy variables from a factor.
For example, the mtcars
dataset has cyl
values 4
, 6
, and 8
. I would like to create a set of variables such as: four_six
with 4
coded as 0
and 6
coded as 1
. I eventually want to create other variables like: six_eight
, four_eight
.
I tried something like this using ifelse
four_six <- ifelse(cyl == 4, 0, 1)
But I would like to recode the sixes as 1
, instead of everything as 1
.
For example, I would like the eights coded as missing/NA.
Also, is there a way to programmatically do this with other functions?
Just add another condition
four_six <- ifelse(cyl == 4, 0, ifelse(cyl==6, 1, NA))
or use dplyr::case_when
four_six <- dplyr::case_when(cyl==4 ~ 0, cyl==6 ~ 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.