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
For that, I tried the following with little success.
library(ade4)
acm.disjonctif(df)
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.
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().
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).
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.
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)
You can do this with reshaping:
library(dplyr)
library(tidyr)
df %>%
mutate(value = 1,
c = paste0("Is", c)) %>%
spread(c, value, fill = 0)
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