Transform variable length list into matrix in R

Viewed 213

If I had a list of vectors of variable lengths :

[[1]]
[1] 1 2 3 4

[[2]]
[1] 4 5 6

[[3]]
[1] 1 2 3 4 5 6 7 8 9

[[4]]
[1] 'a' 'b' 'c'

How could I transform this into a data frame / logical matrix with elements of the list represented as columns?

i.e a dataframe like:

    1 2 3 4 5 6 7 8 9 'a' 'b' 'c'
[1] 1 1 1 1 0 0 0 0 0  0   0   0
[2] 0 0 0 1 1 1 0 0 0  0   0   0
[3] 1 1 1 1 1 1 1 1 1  0   0   0
[4] 0 0 0 0 0 0 0 0 0  1   1   1

some data:

x <- list(c(1, 2, 3, 4), c(4, 5, 6), c(1, 2, 3, 4, 5, 6, 7, 8, 9), c("a", "b", "c"))
3 Answers

Here is a base R option:

# extract unique values from x
uv <- unique(unlist(x)) 
# Check in each element of lists which values are present and bind everything toegether
out <- do.call(rbind, lapply(x, function(e) as.integer(uv %in% e) ))
# Convert from matrix to data.frame and add column names
out <- setNames(as.data.frame(out), uv)
out

  1 2 3 4 5 6 7 8 9 a b c
1 1 1 1 1 0 0 0 0 0 0 0 0
2 0 0 0 1 1 1 0 0 0 0 0 0
3 1 1 1 1 1 1 1 1 1 0 0 0
4 0 0 0 0 0 0 0 0 0 1 1 1

Here is a base R option with stack and table

table(stack(setNames(x, seq_along(x)))[2:1])
#   values
#ind 1 2 3 4 5 6 7 8 9 a b c
#  1 1 1 1 1 0 0 0 0 0 0 0 0
#  2 0 0 0 1 1 1 0 0 0 0 0 0
#  3 1 1 1 1 1 1 1 1 1 0 0 0
#  4 0 0 0 0 0 0 0 0 0 1 1 1

Something like this?

library(tidyverse)
x = list(c(1, 2, 3, 4), c(4, 5, 6), c(1, 2, 3, 4, 5, 6, 7, 8, 9))
y = tibble(column1= map_chr(x, str_flatten, " "))

Where y is this:

# A tibble: 3 x 1
  column1          
  <chr>            
1 1 2 3 4          
2 4 5 6            
3 1 2 3 4 5 6 7 8 9
Related