In a previous post (How do I read multiple JSON structures contained in one file?) I have asked about an uncommon data structure (or at least uncommon for R)
I have a txt file with this structure:
identifier ### part A ### part B
A simplification of the 1st line of my real data would be this
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"}]
This structure comes from public data.
I have used this
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")
And that creates two data frames
PartA
X Y Z
1 2 3
4 5 6
PartB
X Y Z
7 8 9
10 11 12
13 14 15
I have tried to obtain something like this
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
Any idea would be helpful. Many thanks in advance.