【问题标题】:Convert variable length list into edge list igraph R将可变长度列表转换为边缘列表 igraph R
【发布时间】:2016-10-15 23:34:43
【问题描述】:

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

我该怎么做?

【问题讨论】:

    标签: r list variables dataframe igraph


    【解决方案1】:

    如果我们需要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 一次可能比unlisting 'lst' 多次调用更快

    matrix(unlist(lapply(lst, combn, 2)), ncol=2, byrow=TRUE)
    

    【讨论】:

    • 好答案。 unlist 可能会稍微快一点并输入矩阵 - matrix(unlist(lapply(el, combn, 2)), ncol=2, byrow=TRUE) - 不过还没有测试过..
    • 我也有同样的问题,但我的分隔符是分号(文本中带有逗号)并且文本位于数据框值中。也许我会开始另一个问题?
    • 列表名称是什么?是lst
    • @adm 可能您需要将数据框列拆分为,,即do.call(rbind, lapply(strsplit(as.character(data$Col), ","), function(x) t(combn(x, 2))))
    • @adm 因为您可能有一些元素只有一个单词左右。在这种情况下,您需要一个 if/else 条件,即。 if(length(x) > 2) do this else x
    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多