我在R中有一个列表,其中每个元素都有可变数量的字符串,例如:
el: list
chr [1:3] "sales", "environment", "communication"
chr [1:2] "interpersonal", "microsoft office"
chr [1:4] "writing", "reading", "excel", "python"
我想将此列表转换为2列的矩阵,如果它们出现在列表的同一元素中,则将两个字符串并排放置,例如。
matrix:
"sales", "environment"
"sales, "communication"
"environment", "communication"
"interpersonal", "microsoft office"
"writing", "reading"
"writing", "excel"
"writing", "python"
"reading", "excel"
"reading", "python"
"excel", "python"
我该怎么做?
答案 0 :(得分:4)
如果我们需要matrix
中的输出,我们可以使用combn
do.call(rbind, lapply(lst, function(x) t(combn(x, 2))))
# [,1] [,2]
# [1,] "sales" "environment"
# [2,] "sales" "communication"
# [3,] "environment" "communication"
# [4,] "interpersonal" "microsoft office"
# [5,] "writing" "reading"
# [6,] "writing" "excel"
# [7,] "writing" "python"
# [8,] "reading" "excel"
# [9,] "reading" "python"
#[10,] "excel" "python"
或者正如@thelatemail所提到的,通过t
'lst'来多次拨打unlist
一次可能会更快
matrix(unlist(lapply(lst, combn, 2)), ncol=2, byrow=TRUE)