gpt4 book ai didi

r - 将可变长度列表转换为边缘列表 igraph R

转载 作者:行者123 更新时间:2023-12-01 00:41:05 26 4
gpt4 key购买 nike

我在 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 可能会更快。一次多于多次 unlist ing the 'lst'
matrix(unlist(lapply(lst, combn, 2)), ncol=2, byrow=TRUE)

关于r - 将可变长度列表转换为边缘列表 igraph R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37825505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com