在上一篇文章(如何读取一个文件中包含的多个 JSON 结构?)中,我询问了一个不常见的数据结构(或者至少对于 R 来说不常见)
我有一个具有这种结构的 txt 文件:
identifier ### part A ### part B
我的真实数据的第一行的简化是这样的
1 ### [{"X": "1", "Y": "2", "Z": "3"}, {"X": "4", "Y": "5", "Z": "6"}] ### [{"X": "7", "Y": "8", "Z": "9"}, {"X": "10", "Y": "11", "Z": "12"}, {"X": "13", "Y": "14", "Z": "15"}]
这种结构来自公共数据。
我用过这个
setwd("/myfolder")
library(stringi)
library(purrr)
library(jsonlite)
raw <- readLines("myfile.txt")
raw <- gsub("^.\\###", " ", raw)
PartB <- gsub("^.*\\]\\###\\[", "", raw)
PartB <- paste0("[", PartB)
PartB <- stri_replace_first_regex(PartB, "\\###", "") %>%
map_df(fromJSON)
save(fundamento, file = "PartB.RData")
PartA <- gsub(pattern = "(.*\\###)(.*)(\\###.*)", "\\2", raw)
PartA <- stri_replace_first_regex(concepto, "\\###", "") %>%
map_df(fromJSON)
save(PartA, file = "PartA.RData")
这会创建两个数据框
PartA
X Y Z
1 2 3
4 5 6
PartB
X Y Z
7 8 9
10 11 12
13 14 15
我试图获得这样的东西
PartA
identifier part X Y Z
1 A 1 2 3
1 A 4 5 6
PartB
identifier part X Y Z
1 B 7 8 9
1 B 10 11 12
1 B 13 14 15
任何想法都会有所帮助。提前谢谢了。