繁体   English   中英

将可变长度列表转换为R中的矩阵

[英]Transform variable length list into matrix in 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选项:

# 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

这是一个带有stacktablebase R选项

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

像这样的东西?

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

这是y:

# 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM