Last active
February 5, 2016 17:20
-
-
Save vpnagraj/31b39232d75cb29f52a8 to your computer and use it in GitHub Desktop.
shiny gadget that removes outliers based on 'brushed' area of a plot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# install.packages("shiny") | |
# install.packages("miniUI") | |
# install.packages("ggplot2") | |
library(shiny) | |
library(miniUI) | |
library(ggplot2) | |
outlier_rm <- function(data, xvar, yvar) { | |
ui <- miniPage( | |
gadgetTitleBar("Drag to select points"), | |
miniContentPanel( | |
# 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 | |
stopApp(data[-g,]) | |
}) | |
} | |
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") | |
library(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") | |
library(dplyr) | |
outlier_rm(gapminder, "lifeExp", "gdpPercap") %>% | |
group_by(country) %>% | |
summarise(mean(lifeExp)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment