Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting R table to JSON string

Tags:

json

r

I'm learning R and I'm doing a Predictive Analysis API using R, I'm using plumber to create a web API service. I need to retrieve the confusion Matrix of my Naive Bayes prediction result but unfortunately I could not find any method to convert the resulting object (R table object) to a JSON string.

One of my options is to manually create the JSON string, but I can't find the way of iterate through the table, including the row and column names.

This is an example of my table object:

          Active   Inactive   Hotlined   Suspended
Active       1        0          2           1
Inactive     0        2          0           0
Hotlined     3        0          3           2
Suspended    0        5          0           4

And the output that I need is similar to this:

[
   {column:'Active',row:'Active',value:1},
   {column:'Inactive',row:'Active',value:0},
   {column:'Hotlined',row:'Active',value:2},
   {column:'Suspended',row:'Active',value:1},
   .......... #The same for next rows
,]

Also, the table object can have less columns and/or less rows according the prediction result, I think I should mention this before Any idea on how can I achieve this?

like image 799
Oscar_sgc Avatar asked Jan 23 '26 17:01

Oscar_sgc


2 Answers

The answer given by @thelatemail works and gives me the correct String

this is the answer

library(jsonlite)
toJSON(setNames(as.data.frame(tab),c("row","column","value")))

Thanks to all for the help

like image 64
Oscar_sgc Avatar answered Jan 26 '26 09:01

Oscar_sgc


Transform your data to long format and convert to json. Example with tidyr:

library(dplyr)
library(tidyr)
library(jsonlite)

df1 %>% 
  dplyr::add_rownames("row") %>% 
  tidyr::gather(column, value, -row) %>%
  arrange(row) %>% 
  select(column, row, value) %>% 
  toJSON(pretty = TRUE)

# [
#   {
#     "column": "Active",
#     "row": "Active",
#     "value": 1
#   },
#   {
#     "column": "Inactive",
#     "row": "Active",
#     "value": 0
#   },
#   {
#     "column": "Hotlined",
#     "row": "Active",
#     "value": 2
#   },
#
#   ...

Test input created with:

df1 <- read.table(text = "
          Active   Inactive   Hotlined   Suspended
  Active       1        0          2           1
  Inactive     0        2          0           0
  Hotlined     3        0          3           2
  Suspended    0        5          0           4
"
)

I think in your case you will have to convert your table object with as.data.frame.

like image 26
bergant Avatar answered Jan 26 '26 07:01

bergant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!