Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix json code to split in a table using dplyr

I’m trying to split this json code into an easier way to parse my data, I have tried to use jsonlite with fromJSON() but doesn’t work.

Data

{
    "PROB": 0.066977381909206,
    "Y": -3.221016563928024,
    "x": 933
}
library(jsonlite)

jsonStr <- '{
    "PROB": 0.066977381909206,
    "Y": -3.221016563928024,
    "x": 933
}'

t = fromJSON(jsonStr)

> t
$PROB
[1] 0.06697738

$Y
[1] -3.221017

$x
[1] 933

expected output

        PROB         Y   x
1 0.06697738 -3.221017 933

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can create a tibble (data frame) from the parsed JSON data:

library(jsonlite)

jsonStr <- '{
    "PROB": 0.066977381909206,
    "Y": -3.221016563928024,
    "x": 933
}'

t <- fromJSON(jsonStr)

# create an empty data frame to store the result
df <- data.frame()

# loop through each variable in the list
for (name in names(t)) {
  df[name] <- t[[name]]
}

# assign row names
rownames(df) <- "1"

df

Result:

# A tibble: 1 × 3
    PROB     Y     x
   <dbl> <dbl> <int>
1 0.0670 -3.22   933
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading