I'm trying to build a tree which would react when clicking on a row of a datatable. Especially, I would like the corresponding leaf of the tree to be highlighted. How can I achieve that ? Here is a sample code:
library(shiny)
library(DT)
library(shinyTree)
library(shinyjs)
# Data.frame
data <- data.frame(
ID = 1:10,
Name = c("Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Hank", "Ivy", "Jack"),
Age = c(25, 32, 45, 28, 40, 52, 34, 29, 37, 48),
Score = c(85, 92, 78, 88, 76, 95, 81, 89, 70, 93)
)
ui <- fluidPage(
DTOutput("table"),
shinyTree("tree")
)
server <- function(input, output, session) {
# Datatable
output$table <- renderDT({
datatable(data, selection = 'single', rownames = FALSE, callback = JS(
"table.on('click', 'tr', function() {",
" var index = table.row(this).index();",
" Shiny.setInputValue('selected_row', index);",
"});"
))
})
# Reactive highlight on click
observeEvent(input$selected_row, {
### Strunggling from here ###
create_tree(data, c("Age", "Name"))
}
})
}
The tree would be something like this - using renderTree to look good. Such that, when selecting a row, e.g. Bob from the dataframe, the leaf corresponding to Bob is highlighted.
1 Root
2 ¦--25
3 ¦ °--Alice
4 ¦--32
5 ¦ °--Bob
6 ¦--45
7 ¦ °--Charlie
8 ¦--28
9 ¦ °--David
10 ¦--40
11 ¦ °--Eve
12 ¦--52
13 ¦ °--Frank
14 ¦--34
15 ¦ °--Grace
16 ¦--29
17 ¦ °--Hank
18 ¦--37
19 ¦ °--Ivy
20 °--48
21 °--Jack