R2D3 data join not working

I am following the bar graph example on the R2D3 website:

https://rstudio.github.io/r2d3/articles/shiny.html

Instead of updating bars I would like to update my Table Headers when I change the data input. When I run the code the headers are duplicated instead of replaced. Any idea what I am doing wrong?

Shiny

library(shiny)
library(r2d3)
library(tidyr)
library(plyr)
library(dplyr)
options(r2d3.shadow = FALSE)

 #Convert data to JSON format
 data_to_json <- function(data) {
     jsonlite::toJSON(
         data,
         dataframe = "rows",
     auto_unbox = FALSE,
         rownames = TRUE
     )
 }
 
 ui <- fluidPage(
 
     # Application title
     titlePanel("Table Transitions"),
 
     # Sidebar with a slider input for number of bins 
     sidebarLayout(
         sidebarPanel(
             selectInput("data", label="Data Input", choices = c("data 1", "data 2"))
         ),
 
         # Show a plot of the generated distribution
         mainPanel(
             d3Output("table")
         )
     )
 )
 
 # Define server logic required to draw a histogram
 server <- function(input, output) {
 
     output$tableUI <- renderUI({
         input$data
         d3Output(("table"))
         
     })
 
     output$table <- renderD3({
         
         data <- if(input$data == "data 1"){
             data1 <- data.frame(
                 name = c("Chocolate", "Jam", "Sprinkles", "Honey"),
                 rating = c(10, 5, 9, 4),
                 stringsAsFactors = FALSE
             ) %>% arrange(desc(rating))
         
         } else {
             data1 <- data.frame(
                 day = c("Chocolate", "Jam", "Sprinkles", "Honey"),
                 rating = c(5, 10, 4, 9),
                 stringsAsFactors = FALSE
             ) %>% arrange(desc(rating))
         }
         
         r2d3(
             data = data_to_json(data),
             options = list(
             ),
             d3_version = c("5"),
             container = 'div',
             css = "www/chartstyles.css",
             script = "www/tableD3.js",
             dependencies = c(
             )
         )
     })
 }
 
# # Run the application 
shinyApp(ui = ui, server = server)

JS


let table = div.append('table')
let thead = table.append('thead')


const t = d3.transition().duration(1000)
const t2 = d3.transition().duration(2000)

let theadData = thead.selectAll('text')
  .data(d3.keys(r2d3.data[0]).slice(0,-1))

  theadData.enter()
  .append('text')
  .text(d => d)

  theadData.exit().remove()

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.