温馨提示:本文翻译自stackoverflow.com,查看原文请点击:json - How to modify a txt file in R that is not in the correct R format?
json r

json - 如何修改R格式不正确的txt文件?

发布于 2020-03-27 11:45:32

我有几个带有多个数据点的.txt文件,这些文件的头格式不正确,我想取出不必要的数据,以便R可以读取数据。需要删除某些零件,并需要标识X和Y列。这是文本文件读取内容的示例,其中six指的是X组件,siy而指的是Y组件:

{
    "description": "",
    "name": "1ml",
    "references": [
        {
            "siclassids": [
            ],
            "siname": "1ml",
            "sipoints": [
                {
                    "six": 397.32000732421875,
                    "siy": 0.8571428656578064
                },
                {
                    "six": 400.20001220703125,
                    "siy": 0.75
                },
                {
                    "six": 403.08999633789062,
                    "siy": 0.60000002384185791

在几个不同的文件中有数百个这些数据点,请问有什么方法可以组织这些数据并读取图中的数据?

谢谢!

查看更多

查看更多

提问者
Emma Madigan
被浏览
168
jay.sf 2019-07-03 23:45

您可以使用正则表达式。grep标识有趣的线。gsub查找"x""y"以及对应的值,然后将其与组合,strsplit在逗号处分割成一个列表。

l <- readLines("dp.txt")
l <- setNames(do.call(rbind.data.frame, 
        strsplit(gsub(".+si(.)\\D*(\\d+\\.\\d+).+", "\\1, \\2", 
                      l[grep("\\d{2,}", l)]), ",")), c("axis", "coord"))
l$coord <- as.numeric(l$coord)
l
#   axis coord
# 1    x     4
# 2    y     3
# 3    x     5
# 4    y     2
# 5    x     6
# 6    y     1