I have a variable, called gender
, with binary categorical values "female"/"male". I want to change its type to integers 0/1 so that I can use it in a regression analysis. i.e I want values "female" and "male" to be mapped to 1 and 0.
> str(gender)
gender : Factor w/ 2 levels "female","male": 1 1 1 0 0 0 0 1 1 0 ...
> gender[1]
[1] female
I would like to convert gender variable type so that I get int value 1 when I query an element, i.e.
> gender[1]
[1] 1
To change the code “Yes” to 1, we can use ifelse function and set the Yes to 1 and others to 0. For example, if we have a data frame called df that contains a character column x which has Yes and No values then we can convert those values to 1 and 0 using the command ifelse(df$x=="Yes",1,0).
There are two steps for converting factor to numeric: Step 1: Convert the data vector into a factor. The factor() command is used to create and modify factors in R. Step 2: The factor is converted into a numeric vector using as. numeric().
Convert an Integer to a Binary value in R Programming – as. binary() Function. as. binary() function in R Language is used to convert an integer value to a binary value.
Convert to a factor and let R take care of the rest. You should never have to take care of explicitly creating dummy variables when using R.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With