【问题标题】:Create nested list structure from a string从字符串创建嵌套列表结构
【发布时间】:2016-02-12 14:49:33
【问题描述】:

我有一个由 n 个子字符串组成的字符串。它可能看起来像这样:

string <- c("A_AA", "A_BB", "A_BB_AAA", "B_AA", "B_BB", "B_CC")

此字符串中的每个子组件都由“_”分隔。这里,第一级由值“A”和“B”组成,第二级由“AA”、“BB”和“CC”组成,第三级由“AAA”组成。更深的嵌套是可能的,解决方案应该扩展到这些情况。嵌套不一定是平衡的,例如“A”只有两个孩子,“B”有三个孩子,但它还有一个“B”没有的孙子。

本质上,我想在某种 R 对象中重新创建此字符串中的嵌套结构,最好是列表。因此,嵌套列表结构如下所示:

list("A" = list("AA", "BB" = list("AAA")),
"B" = list("AA", "BB", "CC"))

> $A
  $A[[1]]

  [1] "AA"
  $A$BB
  $A$BB[[1]]
  [1] "CCC"

  $B
  $B[[1]]
  [1] "AA"

  $B[[2]]
  [1] "BB"

  $B[[3]]
  [1] "CC"

对此的任何帮助表示赞赏

【问题讨论】:

    标签: r string list


    【解决方案1】:

    你可以把它变成一个矩阵而不用大惊小怪......

    string <- c("A_AA", "A_BB", "A_BB_AAA", "B_AA", "B_BB", "B_CC")
    
    splitted<-strsplit(string,"_")
    cols<-max(lengths(splitted))
    mat<-do.call(rbind,lapply(splitted, "length<-", cols))
    

    【讨论】:

    • 您可以将lapply(x, length) 替换为lengths(x),也可以在“cols”之后使用do.call(rbind, lapply(splitted, "length&lt;-", cols))。
    • 这会导致与 OP 想要的结构截然不同。除非有从矩阵到 OP 格式的微不足道的转换,否则我认为这不是他们所追求的(而且我看不到)。
    • @KonradRudolph OP 确实优先考虑列表列表,但对其他结构似乎很灵活。
    • 感谢您的努力,但我不认为矩阵格式对我很有用。我将需要使用生成的对象来确定 A“节点”下有多少孩子/孙子。我不确定这是否可以通过矩阵轻松实现(抱歉,从一开始就不清楚)。
    • @user3393472 实际上,使用矩阵比使用列表要容易得多。当您在列表上执行 length 时,它会将同样是列表的元素视为 1,它不会计算列表中的所有子元素。而使用矩阵你可以做subset(mat,mat[,1]=="A"),然后计算有多少代列是na。
    【解决方案2】:

    不是那么直截了当,也不是最漂亮的代码,但它应该完成它的工作并返回一个列表:

    string <- c("A_AA", "A_BB", "A_BB_AAA", "B_AA", "B_BB", "B_CC")
    
    # loop through each element of the string "str_el"
    list_els <- lapply(string, function(str_el) {
    
      # split the string into parts
      els <- strsplit(str_el, "_")[[1]]
    
      # loop backwards through the elements
      for (i in length(els):1){
    
        # the last element gives the value
        if (i == length(els)){
    
          # assign the value to a list and rename the list          
          res <- list(els[[i]])
          names(res) <- els[[i - 1]]
    
        } else {
          # if its not the last element (value) assign the list res to another list
          # with the name of that element
          if (i != 1) {
            res <- list(res)
            names(res) <- els[[i - 1]]
          }
        }
      }
    
      return(res)
    })
    
    # combine the lists into one list
    res_list <- mapply(c, list_els, SIMPLIFY = F)
    
    res_list
    # [[1]]
    # [[1]]$A
    # [1] "AA"
    # 
    # 
    # [[2]]
    # [[2]]$A
    # [1] "BB"
    # 
    # 
    # [[3]]
    # [[3]]$A
    # [[3]]$A$BB
    # [1] "AAA"
    # 
    # 
    # 
    # [[4]]
    # [[4]]$B
    # [1] "AA"
    # 
    # 
    # [[5]]
    # [[5]]$B
    # [1] "BB"
    # 
    # 
    # [[6]]
    # [[6]]$B
    # [1] "CC"
    

    这能满足你的需求吗?

    【讨论】:

    • 谢谢,已经很接近了。对于我的问题,有必要 list_els[[1]] 给我整个 A “节点”及其所有子孙
    • 这似乎是一个真正的痛苦。您能否详细说明您要实现的目标。我会通过使用某种非列表结构来坚持@Dean 的回答。列表在某些情况下确实很有用,但嵌套列表就没那么有趣了。
    • 我暂时坚持使用 Dean 的解决方案。感谢您的努力。
    【解决方案3】:

    我找到了这种方法。这很奇怪,但似乎有效

    my_relist <- function(x){
    y=list()
    #This first loop creates the skeleton of the list
    for (name in x){
        split=strsplit(name,'_',fixed=TRUE)[[1]]
        char='y'
        l=length(split)
        for (i in 1:(l-1)){
            char=paste(char,'$',split[i],sep="")
        }
    char2=paste(char,'= list()',sep="")
    #Example of char2: "y$A$BB=list()"
    eval(parse(text=char2))
    #Evaluates the expression inside char2
    }
    
    #The second loop fills the list with the last element
    for (name in x){
       split=strsplit(name,'_',fixed=TRUE)[[1]]
       char='y'
       l=length(split)
       for (i in 1:(l-1)){
           char=paste(char,'$',split[i],sep="")
       }
    char3=paste(char,'=c(',char,',split[l])')
    #Example of char3: "y$A = c(y$A,"BB")"
    eval(parse(text=char3))
    }
    return(y)
    }
    

    结果如下:

    example <- c("A_AA_AAA", "A_BB", "A_BB_AAA", "B_AA", "B_BB", "B_CC")
    my_relist(example)
    #$A
    #$BB
    #1.'AAA'
    #[[2]]
    #'AA'
    #[[3]]
    #'BB'
    #$B
    #1.'AA'
    #2.'BB'
    #3.'CC'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2023-04-06
      • 2017-02-20
      • 2018-11-19
      相关资源
      最近更新 更多