1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | ##---- Should be DIRECTLY executable !! ----
##-- ==> Define data, use random,
##-- or do help(data=index) for the standard data sets.
## The function is currently defined as
hist_addin <- function() {
#.............................
# PRELIMINARIES
#.............................
library(rstudioapi)
library(dplyr)
library(miniUI)
library(ggplot2)
# Function that scans the working space for dataframes
search_df <- function() {
# Container
c <- c()
# Function to tell which place an object has in the workspace
w <- function(x) {
ls <- ls(envir = .GlobalEnv)
return(which(ls == x))
}
# Which object is a dataframe?
for (data in ls(envir = .GlobalEnv)) {
if (any(class(eval(parse(text = data))) == "data.frame")) {
c[w(data)] <- data
}
}
# Return all non-NA values
return(c[!is.na(c)])
# Delete the rest
rm(w)
rm(c)
}
# UI
ui <- miniPage(
gadgetTitleBar("Interactive Histogram"),
fillRow(
miniContentPanel(
# Select Dataset
selectInput(label = "Select your dataset:",
inputId = "dataset",
choices = c("", search_df())),
# Select Variable
uiOutput("choices1"),
# Plot Density
checkboxInput(inputId = "density",
label = "Plot Density"),
# Adjust #bins
sliderInput(inputId = "slider",
label = "Adjust number of bins",
min = 5,
max = 50,
value = 10)
),
miniContentPanel(plotOutput("plot1"))
)
)
server <- function(input, output, session) {
# Was a dataset selected?
data <- reactive({
validate(
need(input$dataset != "", "Please select a data set")
)
get(input$dataset)
})
# Was a numeric variable selected?
variable <- reactive({
validate(
if (is.null(input$variable) == FALSE) {
need(mode(data()[[input$variable]]) == "numeric", "Please pick a numeric variable")
}
)
input$variable
})
# Render the UI button with variable selections, if dataset is selected
output$choices1 <- renderUI({
col.names <- colnames(data())
selectInput(inputId = "variable",
label = "Select your variable",
choices = col.names)
})
# Render Histogram
output$plot1 <- renderPlot({
g <- ggplot(data = data(),
aes_string(x = variable())) +
geom_histogram(aes(y = ..density..),
stat = "bin",
bins = input$slider) +
theme_bw()
if (input$density == TRUE) {
g <- g + geom_density(fill = "firebrick", alpha = .5)
}
g
})
# Stop App if Done Button is pressed
observeEvent(input$done, {
stopApp()
})
}
# Where should the App be viewn?
viewer <- dialogViewer(dialogName = "Histogram Add-In",
height = 600,
width = 900)
runGadget(ui, server, viewer = viewer)
}
{ ~kwd1 }
{ ~kwd2 }
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.