Transforming an R object into a suitable format for the tree layout in d3.js

Following up from a previous question regarding converting ctree output to JSON format for D3 tree layout, I have the following code generated by the use of ctree (from Party package) and I aim to create a recursive function to transform the JSON output.

{"nodeID":[1],"left":{"nodeID":[2],"weights":[50],"prediction":[1,0,0]},"right":{"nodeID":[3],"left":{"nodeID":[4],"left":{"nodeID":[5],"weights":[46],"prediction":[0,0.9783,0.0217]},"right":{"nodeID":[6],"weights":[8],"prediction":[0,0.5,0.5]}},"right":{"nodeID":[7],"weights":[46],"prediction":[0,0.0217,0.9783]}}}

The desired transformation is as follows:

{"name": "1", "children": [{"name": "3","children":[{"name": "4","children":[{"name":"5 weights:[46] prediction:[0,0.9783,0.0217]"},{"name":"6 weights:[8] prediction[0,0.5,0.5]",
{"nodeID":"7 weights:[46] prediction[0,0.0217,0.9783]"}]},{"name": "2 weights:[50] prediction[1,0,0]"}]}

This transformation enables the creation of a visual representation using d3.js https://i.sstatic.net/fcP5Y.png.

Background:

I currently have code that outputs JSON data but it requires further manipulation:


library(party)
irisct <- ctree(Species ~ .,data = iris)
plot(irisct)

get_ctree_parts <- function(x, ...)
{
  UseMethod("get_ctree_parts")
}

get_ctree_parts.BinaryTree <- function(x, ...)
{
  get_ctree_parts(attr(x, "tree"))
}

get_ctree_parts.SplittingNode <- function(x, ...)
{
  with(
    x,
    list(
      nodeID       = nodeID,
      left         = get_ctree_parts(x$left),
      right        = get_ctree_parts(x$right)
    )
  )
}

get_ctree_parts.TerminalNode <- function(x, ...)
{
  with(
    x,
    list(
      nodeID     = nodeID,
      weights    = sum(weights),
      prediction = prediction
    )
  )
}

toJSON(get_ctree_parts(irisct))

Efforts to transform this code face challenges in creating a recursive function for nested JSON objects reflecting the splitting nodes while accommodating different navigation conventions between ctree and d3.js.

Any assistance on resolving these challenges would be greatly appreciated!

Answer №1

Hey there, I just recently delved into R coding after coming across a post and wanted to share my progress so far.

library(party)
irisct <- ctree(Species ~ .,data = iris)
plot(irisct)

get_ctree_parts <- function(x, ...)
{
  UseMethod("get_ctree_parts")
}

get_ctree_parts.BinaryTree <- function(x, ...)
{
  get_ctree_parts(attr(x, "tree"))
}

get_ctree_parts.SplittingNode <- function(x, ...)
{
  with(
    x,
    list(
      name       = toString(nodeID),
      children   = list(get_ctree_parts(x$left),get_ctree_parts(x$right))

    )
  )
}

get_ctree_parts.TerminalNode <- function(x, ...)
{
  with(
    x,
    list(
      name     = paste(nodeID,"weights",sum(weights),"prediction",toString(paste("[",toString(prediction),"]",sep=" ")),sep = " ")

    )
  )
}

toJSON(get_ctree_parts(irisct))

Json Output:

{"name":["1"],"children":[
    {"name":["2 weights 50 prediction [ 1, 0, 0 ]"]},
        {"name":["3"],"children":[
            {"name":["4"],"children":[
                {"name":["5 weights 46 prediction [ 0, 0.978260869565217, 0.0217391304347826 ]"]},
                {"name":["6 weights 8 prediction [ 0, 0.5, 0.5 ]"]}]
            },
            {"name":["7 weights 46 prediction [ 0, 0.0217391304347826, 0.978260869565217 ]"]
            }]
        }]
} 

If you encounter any issues, feel free to leave a comment and I'll do my best to assist you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for generating a mirrored bar plot in R with two variables on either side of the x-axis?

In my dataset, I have three columns representing the x variable and two y variables (y1 and y2). My goal is to create a bar plot where y1 is plotted above the x axis and y2 is mirrored below it for the same x values. Example D in the figure below demonstr ...

Resizing an image with six corners using the canvas technique

Currently, I am facing two issues: The topcenter, bottomcenter, left and right anchors are not clickable. I'm struggling with the logic to adjust the image size proportionally as described below: The corner anchors should resize both height and wi ...

What is the Vue.js alternative to using appendChild for dynamically inserting new elements or components?

When working with Vue.js, I have successfully created a var app = new Vue({...}); and defined a component Vue.component('mycomponent', .... I am able to use this component by directly adding <mycomponent></mycomponent> in my HTML. How ...

Prevent Symfony2 Twig from rendering HTML content

Is there a way to disable the rendering of HTML responses in Twig? I am currently working on a RESTful API and my goal is to completely prevent HTML rendering. For instance, if I access /foo/bar without an oAuth Access Token, Symfony2 should reply with a ...

Issue encountered while appending text input fields to an HTML form dynamically using JavaScript

In the process of developing a mobile web service that allows employees to log their working hours using their phones, I have incorporated a form created through a php loop function. This loop dynamically populates the form with each day of the week. Worki ...

Unable to locate the module '/workspace/mySQL/node_modules/faker/index.js'

Hi there, I'm currently facing an issue while trying to run the app.js file in my project through the terminal. It keeps showing me an error message that I am unable to resolve. To provide some context, I have already installed the faker package using ...

What are the reasons behind the inability to import an image file in Next.js?

Having an issue with importing image file in Next.js I'm not sure why I can't import the image file... The image file is located at 'image/images.jpg' In Chrome browser, there are no error messages related to the image, However, in ...

Utilizing a checkbox within a select dropdown component in Vue

Has anyone come across a checkbox dropdown feature in Vue? I have been searching online but couldn't find any examples or resources related to this. If someone has a working skeleton for it, please share! ...

Having trouble with JQuery's append method on the <head> tag?

I am having an issue with this particular code block. It seems to be unable to insert the meta tag into the head section. Any suggestions on how to resolve this problem? <html> <head> <title>hello world</title> </head> < ...

Utilize React Helmet for Dynamic Page Titles

Currently, I am utilizing Gatsby with react-helmet to manage the title and meta tags in the head of my website. However, I am eager to find a way to also display this title in the actual text of the page through a global <Header /> component. In proj ...

Display crosses on leaflet map in R Shiny for data points

I'm attempting to display points as crosses (+) on a leaflet map. I've started following the example here. I have two specific things I need help with; 1) Why are all the points not showing up as crosses? 2) Can I lock the marker size so that t ...

Update an array of objects by incorporating additional properties from another array, even if the two arrays are of different lengths. When the iteration of the array is complete, it should

Is there a way to merge two arrays of objects with different keys? I want to combine the keys of the second array with those of the first one. How can I accomplish this task? $scope.links = [ { name: 'JRD', status: 'active ...

Encountering issues with implementing router.push in Reactjs

Currently, I am working on ReactJS and utilizing Next.js. My current task involves refreshing the page (using routes), but I encountered an error message stating: Error: No router instance found. You should only use "next/router" inside the client-side of ...

The Vuex commit has exceeded the maximum calstack size limit

Currently facing an issue https://i.sstatic.net/l1WWH.png The error seems to be isolated to this specific section mounted() { this.$nextTick(() => { let ctx = this.$refs.canvas.getContext('2d') let { chartType, dataOptions ...

What is the reason behind the linking or appearance together of src/pages in Visual Studio Code?

As I venture into the world of Visual Studio Code (VSC) and follow a Gatsby tutorial, I've noticed that every time I create a new directory, VSC seems to automatically link src/pages together. However, my preference is for pages to be a subfolder of s ...

Access to Orders on Shopify has been denied due to a GraphQL error

When trying to fetch orders with '@shopify/koa-shopify-auth', I encountered an error. [GraphQL error: access denied] The query I used is as follows: query { orders(first:2) { edges { node { id name } } } ...

set ajax url dynamically according to the selected option value

My form features a select box with three distinct choices <select id="tool" name="tool"> <option value="option1">Option1</option> <option value="option2">Option2</option> <option value="option3">Option3</ ...

Is there a method to navigate through nested JSON accessors without prior knowledge of the nested keys? The table is encountering an error

How to Handle Nested JSON Accessors in React Table Without Knowing Keys const columns = Object.keys(data).map(key=>{ return { Header: key, accessor: key } }); <ReactTable ...

What could be causing the issue with React Router not functioning properly in Material UI?

I'm currently working on creating a tab and adding routing inside the first tab. However, I am facing an issue where the desired page does not display after clicking on the link. Strangely, upon refreshing the page, the corresponding page appears as e ...

Is it possible to rerun the $onInit function within a different method?

I am facing an issue where I have two different grids both calling the same controller and grid component. My goal is to show/hide a checkbox in one grid based on a certain condition. However, since the gridOptions are loaded during the OnInit method initi ...