从字符串创建嵌套列表结构 [英] Create nested list structure from a string

查看:73
本文介绍了从字符串创建嵌套列表结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a string that is a composite of n substrings. It could look like this:

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

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

Every subcomponent in this string is separated from any other by "_". Here, the first level consists of the values "A" and "B", the second level of "AA", "BB" and "CC", the third level of "AAA". Deeper nestings are possible and the solution should extend to those cases. The nestings are not necessarily balanced, e.g. "A" only has two children, while "B" has three, but it also has a grandchild which "B" has not.

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

Essentially, I want to recreate the nested structure in this string in some kind of R object, preferably a list. Thus, the nested list structure that would look like this:

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"

对此有任何帮助

推荐答案

您可以将其制作成矩阵而不必大惊小怪...

You can make it into a matrix without too much fuss...

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))

这篇关于从字符串创建嵌套列表结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆