我在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"


我该怎么办?

最佳答案

如果需要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)

10-07 19:16
查看更多