将带有整数的列转换为 R 中的二进制矩阵

Converting Column with Integers to Binary Matrix in R

这是我的第一次堆栈溢出 post,所以希望格式可以接受!

我有一个 n x 1 tibble 包含整数,例如:

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 

我想旋转这个 tibble 使其看起来像:

###  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

后一个标题的第一行在“3”列中有一个 1,因为第一个标题的第一行有一个 3。后一个 tibble 的第二行在“2”列中有一个 1,因为第一个 tibble 在第一行有一个 2。后一个小标题的第三行在“6”列中有一个 1,因为第一个小标题在第三行中有一个 6。等等

我认为 tidyr::pivot_wider() 可能有用,因为它创建了正确的列,但我不知道如何有效地填充行。

非常感谢您的帮助!如果我需要澄清一些事情,请告诉我。

使用 base R

中的 model.matrix
model.matrix(~ integer - 1, tibble)

使用pivot_wider,我们可能需要创建一个序列列

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)