0

I am trying to render some d3 graphs in r. I'd like to maintain control over the js so all I want to do is convert my data into a format that the js will take (rather than use a package that will do everything for me)

I dont seem to be able to get the nesting I am looking for using the following:

myfile<-data.frame(paste0(iris$Species,".",row.names(iris)),iris$Sepal.Length*100,stringsAsFactors = FALSE)
        names(myfile)<-c("id","value")
        mydata<-jsonlite::toJSON(myfile,pretty=TRUE)

which gives me

{
   "id": "Species.virginica.149",
    "value": 620
  },
  {
    "id": "Species.virginica.150",
    "value": 590
  }

whereas i would like the species to be the parent and number after the species to be the child with the value being the value of that child.

In the end I want to create a treemap like this one so I suppose i am looking for a way to get data in the format required by this treemap (ie the same format as here

1 Answer 1

2

To get a nested json you have to nest your dataframe, e.g. using tidyr::nest. Try this:

library(dplyr)
library(tidyr)

myfile <- iris %>%
  mutate(id = row.names(iris)) %>% 
  select(id, Species, value = Sepal.Length) %>% 
  group_by(Species) %>% 
  tidyr::nest() %>% 
  rename(children = data)

mydata <- jsonlite::toJSON(myfile, pretty = TRUE)
mydata
#> [
#>   {
#>     "Species": "setosa",
#>     "children": [
#>       {
#>         "id": "1",
#>         "value": 5.1
#>       },
#>       {
#>         "id": "2",
#>         "value": 4.9
#>       },
#>       {
#>         "id": "3",
#>         "value": 4.7
#>       },

#> ...
#> ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.