Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a factor with 2 levels to binary values 0/1 in R [closed]

Tags:

r

binary

r-factor

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
like image 319
user2093989 Avatar asked Feb 21 '13 05:02

user2093989


People also ask

How do I change a variable from 0 to 1 in R?

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).

How do I convert factors to variables in R?

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().

How do I convert to binary in R?

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.


1 Answers

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.

like image 173
Dason Avatar answered Oct 05 '22 06:10

Dason