Skip to content

Instantly share code, notes, and snippets.

Last active Feb 5, 2016
What would you like to do?
shiny gadget that removes outliers based on 'brushed' area of a plot
# install.packages("shiny")
# install.packages("miniUI")
# install.packages("ggplot2")
outlier_rm <- function(data, xvar, yvar) {
ui <- miniPage(
gadgetTitleBar("Drag to select points"),
# The brush="brush" argument means we can listen for
# brush events on the plot using input$brush.
plotOutput("plot", height = "100%", brush = "brush")
server <- function(input, output, session) {
# Render the plot
output$plot <- renderPlot({
# Plot the data with x/y vars indicated by the caller.
ggplot(data, aes_string(xvar, yvar)) + geom_point()
# Handle the Done button being pressed.
observeEvent(input$done, {
# create id for data
data$id <- 1:nrow(data)
# Return the brushed points. See ?shiny::brushedPoints.
p <- brushedPoints(data, input$brush)
# create vector of ids that match brushed points and data
g <- which(p$id %in% data$id)
# return a subset of the original data without brushed points
runGadget(ui, server)
# run to open plot viewer
# click and drag to brush
# press done return a subset of the original data without brushed points
# install.packages("gapminder")
outlier_rm(gapminder, "lifeExp", "gdpPercap")
# you can also use the same method above but pass the output into a dplyr pipe syntax
# without the selection what is the mean life expectancy by country?
# install.packages("dplyr")
outlier_rm(gapminder, "lifeExp", "gdpPercap") %>%
group_by(country) %>%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment