首页 > 解决方案 > 将可变长度列表转换为R中的矩阵

问题描述

如果我有一个可变长度的向量列表:

[[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'

如何将其转换为数据框/逻辑矩阵,列表元素表示为列?

即一个数据框,如:

    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

一些数据:

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"))

标签: r

解决方案


这是一个基本的 R 选项:

# 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

推荐阅读