How to Convert Factor Into Multiple Binary Columns

library(dplyr)
library(tidyr)
iris %>% 
  as_tibble %>% 
  mutate(
  bin = 1, 
  Species = factor(paste0("_is_", Species))) %>%
  spread(
    key = Species, 
    value = bin, 
    fill = 0)

doesn't work but model.matrix does:
model.matrix(object = ~ Species - 1, data = iris)

pivot_wider is the new spread in town...

iris %>% 
  as_tibble %>% 
  mutate(
    bin = 1, 
    Species = factor(paste0("_is_", Species))) -> iris2

pivot_wider(iris2,names_from = Species,
            values_from = bin ,
            values_fill = list(bin=0),
            values_fn =list(bin=function(x){head(x,1)}))
1 Like