解析由多个空格分隔的数据集并将其存储在正确的数据结构中

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

我有一个包含名称,年龄和公司的大型数据集。

file.txt:

name firstname1 lastname1
age 30
Company ABC Ltd

name firstname2 lastname2
age 28
Company XYZ Ltd

我需要编写一个函数,该函数将返回给定键属性的数据结构,并提供给定键的相应值。

例如

 content <- parseFile("file.txt")
 content[1]["name"]    # "firstname1 lastname1"
 content[1]["age"]     # 30
 content[1]["Company"] # "ABC Ltd"

 content[2]["name"]    # "firstname2 lastname2"
 content[2]["age"]     # 28
 content[2]["Company"] # "XYZ Ltd"

到目前为止,我推断可以使用命名向量的列表或可以使用对象列表。

或者有没有更好的方法来解决这个问题?

解释代码示例将很有帮助

r data-structures text-parsing
1个回答
1
投票

我们可以使用readLines获取数据,使用sub创建定界符并创建两列data.frame

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