r - 将可变长度列表转换为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
推荐阅读
- python - 并行计算时无法识别导入的包?
- mysql - 仅当高于 0 时才计算每列的最小值和最大值之间的差异
- javascript - Javascript过滤器和一些对象数组
- angular - 将 mat-button-toggle-group 与内容投影一起使用
- c# - 测试搜索结果的方法
Azure.Search.Documents v11.2.0 中的类 - javascript - ES6 导入/导出变量有问题
- powershell - 无法删除自动驾驶仪配置文件,因为它在 intune 中仍处于活动状态(但已在 intune 中删除)
- powershell - PowerShell:为什么 Get-Unique 只返回集合中的第一个对象?
- python-3.x - 从 python 中的不同目录导入模块时遇到问题
- php - Laravel:从模块扩展视图