0

I am trying to convert a column in a data extract in to a data.frame

Lets say in the table extract, I have a column extract$stage of type: character , the first 11 rows of which looks similar to the following

extract <- read.table (text = 
'stage
{"Stages":{"SBS":{"Type":"N/A","Max":"N/A"}}}
{"Stages":{"SBS":{"Type":"N/A","Max":"N/A"}}}
{"Stages":{"SBS":{"Type":"N/A","Max":"N/A"}}}
{"Stages":{"SBS":[{"Type":"Land","Max":"60%"},{"Type":"Dcon","Max":"70%"},{"Type":"Finish","Max":"80%"}]}}
{"Stages":{"SBS":{"Type":"N/A","Max":"N/A"}}}
{"Stages":{"SBS":{"Type":"N/A","Max":"N/A"}}}
{"Stages":{"SBS":{"Type":"N/A","Max":"N/A"}}}
{"Stages":{"SBS":{"Type":"N/A","Max":"N/A"}}}
{"Stages":{"SBS":[{"Type":"Land","Max":"80%"},{"Type":"Dcon","Max":"80%"},{"Type":"Finish","Max":"80%"}]}}
{"Stages":{"SBS":{"Type":"N/A","Max":"N/A"}}}
{"Stages":{"SBS":{"Type":"N/A","Max":"N/A"}}}',
header = T, stringsAsFactors = F)

What I want at the end is a dataframe that has the same number of rows, but extra columns, such that the end structure dynamically captures any of the inner nest fields and I get 11 rows of this layout:

Record Type.NA Max.NA  Type.Land Max.Land  Type.Dcon  Max.Dcon   Type.Finish Max.Finish
1      NA       NA       NA         NA         NA     NA         NA          NA
...
4      NA       NA       Land       60%        Dcon   70%        Finish      80%

I've tried combinations of jsonlite::fromJSON and do.call.

I can get to a list from the first, via

lapply(extract$stage, jsonlite::fromJSON)

but I'm unable to spread this out in to multiple columns.

Can anyone help?

Thanks!

Jon
  • 445
  • 3
  • 15

1 Answers1

0

Self solved, rather by luck:

lapply(extract$stage, jsonlite::fromJSON) -> ex1
do.call(bind_rows, lapply(ex1, unlist)) -> ex2
ex2

... though happy to see if someone has a neater solution!

Jon
  • 445
  • 3
  • 15