Converting Column with Integers to Binary Matrix in R

Viewed 69

This is my first stack overflow post, so hopefully the formatting is acceptable!

I have a n x 1 tibble containing integers such as:

tibble <- tibble(integer = c("3","2","6","3","5","5","1","2","1","5","2"))
tibble
###  A tibble: 11 x 1
##    integer
##    <chr>  
##  1 3      
##  2 2      
##  3 6      
##  4 3      
##  5 5      
##  6 5      
##  7 1      
##  8 2      
##  9 1      
## 10 5      
## 11 2 

I want to pivot this tibble so that it looks like:

###  A tibble: 11 x 11
##    `1`   `2`   `3`   `4`   `5`   `6`  
##    <chr> <chr> <chr> <chr> <chr> <chr>
##  1 0     0     1     0     0     0
##  2 0     1     0     0     0     0
##  3 0     0     0     0     0     1
##  4 0     0     1     0     0     0
##  5 0     0     0     0     1     0
##  6 0     0     0     0     1     0
##  7 1     0     0     0     0     0
##  8 0     1     0     0     0     0
##  9 1     0     0     0     0     0
## 10 0     0     0     0     1     0
## 11 0     1     0     0     0     0

The first row of this latter tibble has a 1 in the "3" column since the first tibble had a 3 in the first row. The second row of this latter tibble has a 1 in the "2" column since the first tibble had a 2 in the first row. The third row of this latter tibble has a 1 in the "6" column since the first tibble had a 6 in the third row. Etc.

I think that tidyr::pivot_wider() might be useful since it creates the correct columns, but I do not know how to efficiently populate the rows.

Thanks so much for any help! Let me know if I need to clarify something.

1 Answers

Use model.matrix from base R

model.matrix(~ integer - 1, tibble)

Using pivot_wider, we may need to create a sequence column

library(dplyr)
library(tidyr)
tibble %>%
    mutate(rn = row_number(), 
           integer = factor(integer, levels = 1:6)) %>%
    pivot_wider(names_from = integer, values_from = integer, 
         values_fn = length, values_fill = 0) %>%
    select(-rn)
Related