Saving output from brushedPoints as object in R

ggplot2
shiny

#1

I want to select data from an interactive chart using brushedPoints, and have found the following article extremely useful:

https://shiny.rstudio.com/articles/selecting-rows-of-data.html

This does just want I want, allowing me to select points on a chart, and returning the rows for those points.

However, I would like to export or save those rows as an object in R, but am having trouble figuring out how to do so. At the moment they are just printed as an output on the html document.

Any pointers would be much appreciated.

Thanks


#2

Hi @rw2,

Does this help?

ui <- basicPage(
  plotOutput("plot1", brush = "plot_brush"),
  verbatimTextOutput("info")
)
server <- function(input, output) {
  x <- NULL
  output$plot1 <- renderPlot({
    plot(mtcars$wt, mtcars$mpg)
  })
  output$info <- renderPrint({
    x <<- brushedPoints(mtcars, input$plot_brush, xvar = "wt", yvar = "mpg")
    x
  })
}

shinyApp(ui, server)

#3

Thank you for your reply.

It looks like this should write output to the “x” object, which is what I would like to do. However, when I run it, the x object never appears. The console continues to say “Listening on http://…” but no output is ever generated, except as text in the html. Am I missing something obvious?


#4

Oh, you mean in the Environment tab inside RStudio? If that’s the case, then it makes sense that it doesn’t show an x variable because the instance of the Shiny app runs in a completely separate R environment as your script. To persist the data, you’ll probably need to write the selection to a file and the load the file inside the script, although I’m not 100% sure of a valid case for that


#5

Yes, ideally I’d like it to write an object in the Rstudio environment. However, I’d be happy if it just write the selection to a csv file if that’s easier to do. Basically, I’m after any way to get the selected data, without having to copy/paste it from the html.
Thanks!


#6

oh, then just add the line: write.csv(x, "myselection.csv") before passing back x and you should be good to go


#7

Yes, that will do the job! Thanks