Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting factors to binary in R

Tags:

r

I am trying to convert a factor variable into binary / boolean (0 or 1).

Sample data:

df  <-data.frame(a = c(1,2,3), b = c(1,1,2), c = c("Rose","Pink","Red"), d = c(2,3,4))

Trying to transform it like this: a,b,IsRose,IsPink,IsRed,d

Actuals Vs Expected Result

For that, I tried the following with little success.

library(ade4)
acm.disjonctif(df)
like image 354
prasanth Avatar asked Nov 30 '15 02:11

prasanth


People also ask

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.

How do I convert a factor to a numeric 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 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 multiple variables in R?

In R, you can convert multiple numeric variables to factor using lapply function. The lapply function is a part of apply family of functions. They perform multiple iterations (loops) in R. In R, categorical variables need to be set as factor variables.


2 Answers

Just for completeness, building up on this solution (https://stackoverflow.com/a/33990970/2725773), here's an update with the latest tidyverse packages.

library(tidyverse)

df %>%
  mutate(value = 1,
         c = paste0("Is", c)) %>%
  pivot_wider(names_from  = c,
              values_from = value,
              values_fill = 0)
like image 74
deschen Avatar answered Sep 18 '22 19:09

deschen


You can do this with reshaping:

library(dplyr)
library(tidyr)

df %>%
  mutate(value = 1,
         c = paste0("Is", c)) %>%
  spread(c, value, fill = 0)
like image 22
bramtayl Avatar answered Sep 19 '22 19:09

bramtayl