1

Do you need to have "js" package installed in R to run javascript code chunks in an R flexdashboard using crosstalk?

Example code: (taken from another post)

    
    ---
    output:
      html_document
    ---
    
    ```{r echo=FALSE, message=FALSE, warning=FALSE}
    
    
    library(plotly)
    # example data 
    dat <- tibble::tribble(~filterBy, ~x, ~y,
                        "a", 1, 1,
                        "b", 2, 1,
                        "a", 1, 2,
                        "b", 2, 2,
                        "a", 1, 3,
                        "b", 2, 3,
                        "a", 1, 2,
                        "b", 2, 3,
                        "c", 3, 1,
                        "c", 3, 2,
                        "c", 3, 3
                        )  
    
    # initializing a crosstalk shared data object  
    plotdat <- highlight_key(dat)
    
    # Filter dropdown
    question_filter <- crosstalk::filter_select(
       "lantern", "Select a group to examine",
       plotdat, ~filterBy, multiple = F
    )
    
    # Plotting:
    plot <-  plot_ly( plotdat, 
        x = ~x, y = ~y, text = ~filterBy,  mode = "markers+text", 
        textposition = "top", hoverinfo = "x+y"
      )
    ```
    
    ```{js}
    function filter_default() {
        document.getElementById("lantern").getElementsByClassName("selectized") 
    [0].selectize.setValue("bulb", false);
     }
    window.onload = filter_default;
    ```

The filter_default is not working in my code, however the "js" library will not load. Could this be the issue?

lilblue
  • 84
  • 7

1 Answers1

1

The only way that crosstalk is going to work is with shared data. It's unlikely that your call for getElementByID would work either way because your filter isn't activated. If it were, it's highly likely that the dropdown is behind a shadowdom.

highlight is a function from Plotly, not crosstalk.

library(plotly)
library(crosstalk)

sd <- SharedData$new(dat)

question_filter <- crosstalk::filter_select(
  "lantern", "Select a group to examine",
  sd, ~filterBy, multiple = F)  # <---- data changed to shared data


# Plotting:
plot <-  plot_ly(sd,  # <---- data changed to shared data
                 x = ~x, y = ~y, text = ~filterBy,  mode = "markers+text", 
                 textposition = "top", hoverinfo = "x+y")

plot
bscols(plot, question_filter) # combine crosstalk elements

enter image description here

If you weren't aware, there are many ways to make dropdowns, make data selections, and all that with RMarkdown that don't involve crosstalk. However, this library does make things pretty easy.

Kat
  • 15,669
  • 3
  • 18
  • 51
  • Hello! Great answer! I am working on a similar problem https://stackoverflow.com/questions/74076335/r-adding-a-search-bar-to-plotly - do you have any ideas on what might be wrong? Thank you! – stats_noob Oct 16 '22 at 03:56