R:解析和存储以空格分隔的分层结构化数据以及快速搜索和快速访问

问题描述 投票:0回答:1

我有一个大型数据集,其中包含多个字段,其值以空格分隔。然后,将这些字段组合在一起以创建一条记录,并且每个记录可以具有可变长度的子项(带有标签)。

文件内容看起来像这样:

company Samsung
type private
based South Korea

    company Harman International
    type private
    based United States
    industry Electronics

        company JBL
        type subsidiary
        based United States
        industry Audio

company Amazaon
type public
based United States
industry Cloud computing, e-commerce, artificial intelligence, consumer electronics

我想在保持层次结构的同时存储这些记录,并可以选择进行快速搜索和访问每条记录的方式。

到目前为止,我想到了这种方法:

# reading file from the source
path <- "/path/to/file.txt"
content <- readLines(path, warn = F)


# replaces , with ; so it does not translate it as a separator in next step
content <- gsub(",", ";", content)

# creating list of fields and value
contentList <- read.csv(text=sub(" ", ",", content), header=FALSE)

# replacing ; with , to revert data in right format
contentList$V2 <- gsub(";", ",", contentList$V2)

在上述步骤contentList之后,看起来像这样:

contentList output

在下一步中,我考虑使用将使用这些规则创建列表的函数:

  1. 如果该字段没有任何\t,则将其添加到列表中(作为命名向量)
  2. 如果该字段具有一个或多个\t,使其成为先前记录的子列表(作为命名向量)
  3. 但是不知道如何在R中实现。

我应该如何实施?

或者是否有更好的方法来解决此问题,该问题可以快速执行搜索和访问值?

我有一个大型数据集,其中包含多个字段,其值以空格分隔。然后将这些字段组合成一条记录,每条记录可以具有可变长度的子项...

r nested-lists
1个回答
0
投票

原始数据输入

© www.soinside.com 2019 - 2024. All rights reserved.