如果我有一个可变长度的向量列表:
[[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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句