Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How transform a factor to numeric binary variable?

I have a column with different types of sites (factor) :

Localisation
     A  
     A  
     B  
     A 
     B 
     B

I would like to create a new column with binary values (numeric) who correspond to Localization column : A = 1 and B = 0

Localisation Binom 
     A         1
     A         1
     B         0
     A         1
     B         0
     B         0

Thanks !

like image 877
Manon Billard Avatar asked Jan 26 '23 03:01

Manon Billard


1 Answers

dplyr approach, handy when there are more than two if-else conditions.

df <- read.table(stringsAsFactors = T, header = T, text = "Localisation
+      A  
+      A  
+      B  
+      A 
+      B 
+      B")

df %>% mutate(Binom = case_when(Localisation == "A" ~ 1, #condition1
                                Localisation == "B" ~ 0) #condition2
             )
like image 178
massisenergy Avatar answered Jan 29 '23 10:01

massisenergy