I am struggling in writing this shinyApp. It's main aim is to investigate on the variables of a dataset. First it produces the summary statistics on the selected variable.
In the second part; I want this app to give me the pairplot of the varibles that I have selected in the checkbox in the UI. I have used the dataset IRIS which is available to everyone, but I need the code to be adaptable to other datasets.
Can someone please help me?
library(shiny)
library(plotly)
data(iris)
ui<-fluidPage(
titlePanel("Iris"),
sidebarLayout(
sidebarPanel(
selectInput("var",label="Choose a variable",
choice=list("Sepal.Length"=1, "Sepal.Width"=2, "Petal.Length"=3, "Petal.Width"=4, "Species"=5), selectize=FALSE),
checkboxGroupInput(inputId ="independent",label = "Select independent variables", choices = names(iris)),
mainPanel(
verbatimTextOutput("sum"),
plotlyOutput('plot_id_in_ui ', height = "900px")
)
))
)
server<-function(input,output){
output$sum <- renderPrint({
summary(iris[, as.numeric(input$var)])
})
output$plot_id_in_ui <- renderplot( { "DON'T KNOW HOW TO WRITE THIS PART"
pairplot(iris, varnames, type = "both", penalty.par.val = "lambda.1se",
nvals = c(20, 20), pred.type = "response") } )
})
shinyApp(ui, server)
Maybe this little example can help you. It illustrates how to plot a normal R-Plot and a Plotly-Plot in a ShinyApp:
library(shiny)
library(plotly)
ui <- fluidPage(
titlePanel("Iris"),
sidebarLayout(
sidebarPanel(
selectInput("var",label="Choose a variable",
choice=list("Sepal.Length"=1, "Sepal.Width"=2, "Petal.Length"=3, "Petal.Width"=4, "Species"=5), selectize=FALSE),
checkboxGroupInput(inputId ="independent",label = "Select independent variables", choices = names(iris))
),
mainPanel(
verbatimTextOutput("sum"),
plotOutput("plot"),
plotlyOutput("plotly")
)
)
)
server <- function(input,output) {
output$sum <- renderPrint({
summary(iris[, as.numeric(input$var)])
})
output$plot <- renderPlot({
plot(iris)
})
output$plotly <- renderPlotly({
plot_ly(iris) %>%
add_trace(x=iris$Sepal.Length, y=iris$Sepal.Width, type="scatter", mode="markers")
})
}
shinyApp(ui, server)
Related
I use R shiny to create multiple tabs for the scatter plot of different variables in a single app. My code seems alright, but the error says I have not "defined my main panel."
Can someone please help where I have gone wrong, or if my whole approach is inaccurateenter code here, please let me know!
library(shiny)
library(tidyverse)
India <- read.csv("D:/R/Practice 3/Indiadata.csv")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Deaths vs all variables "),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("Deaths", "All variables:",
choices = c("cases"="total_cases","vaccinations"="total_vaccinations",
"people vaccinated"="people_vaccinated","people fully vaccinated"="people_fully_vaccinated",
"total booster"="total_boosters","new vaccinations"="new_vaccinations", "median age"="median_age"))
)
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel(plotOutput("plot1")),
tabPanel(plotOutput("plot2")),
tabPanel(plotOutput("plot3")),
tabPanel(plotOutput("plot4")),
tabPanel(plotOutput("plot5")),
tabPanel(plotOutput("plot6")),
tabPanel(plotOutput("plot7"))
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=total_cases))
})
output$plot2 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=total_vaccinations))
})
output$plot3 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=people_vaccinated))
})
output$plot4 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=people_fully_vaccinated))
})
output$plot5 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=total_boosters))
})
output$plot6 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=new_vaccinations))
})
output$plot7 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=median_age))
})
}
# Run the application
shinyApp(ui = ui, server = server)
mainPanel is an argument of the sidebarLayout() function. So, you just need to move it up into the sidebarLayout() function:
ui <- fluidPage(
# Application title
titlePanel("Deaths vs all variables "),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("Deaths", "All variables:",
choices = c("cases"="total_cases","vaccinations"="total_vaccinations",
"people vaccinated"="people_vaccinated","people fully vaccinated"="people_fully_vaccinated",
"total booster"="total_boosters","new vaccinations"="new_vaccinations", "median age"="median_age"))
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel(plotOutput("plot1")),
tabPanel(plotOutput("plot2")),
tabPanel(plotOutput("plot3")),
tabPanel(plotOutput("plot4")),
tabPanel(plotOutput("plot5")),
tabPanel(plotOutput("plot6")),
tabPanel(plotOutput("plot7"))
)
)
)
)
I'm exploring shiny and I'm trying to do some app that does the following:
Let the user choose between two (or more) different data.frames (in my example I use mtcars and iris but I'm planning to use some self-made data.frames.
Select some X and Y variables according to the data.frame selected
Plot a simple x-y scatterplot
Code below:
df_list <- list(cars= mtcars, iris= iris)
ui <- fluidPage(
titlePanel("Simple app"),
sidebarLayout(
sidebarPanel(
selectInput("data", "Choose a database",
choices=ls(df_list), selected=ls(df_list[1])),
selectInput("xcol", "Variable X", names(data)),
selectInput("ycol", "Variable Y", names(data))),
mainPanel(
plotOutput(outputId = "plot")
)
)
)
server <- function(input, output) {
selectedData <- reactive( {
data[, c(data$xcol, data$ycol)]
})
output$plot <- renderPlot({plot(selectedData())})
}
shinyApp(ui, server)
I feel I have two problems. The first one is pretty obvious since I can't make the app displays variables according to the data.frame selected. Second one is that I feel I'm missing something in my server function (I guess that's related with my first problem) so no plot is displayed.
Any help will be much appreciated.
You had a few issues. The following should work.
df_list <- list("mtcars", "iris")
ui <- fluidPage(
titlePanel("Simple app"),
useShinyjs(),
sidebarLayout(
sidebarPanel(
selectInput("data", "Choose a database",
choices=df_list, selected=df_list[[1]]),
selectInput("xcol", "Variable X", c()),
selectInput("ycol", "Variable Y", c())),
mainPanel(
plotOutput(outputId = "plot")
,DTOutput("t1")
)
)
)
server <- function(input, output, session) {
mydata <- eventReactive(input$data, {
get(input$data)
})
observeEvent(input$data, {
req(mydata())
choices <- names(mydata())
updateSelectInput(session,"xcol",choices = choices, selected=choices[1])
updateSelectInput(session,"ycol",choices = choices, selected=choices[2])
}, ignoreNULL = FALSE)
output$t1 <- renderDT({mydata()})
output$plot <- renderPlot({
req(mydata(),input$xcol,input$ycol)
if (is.null(mydata()) | !(input$xcol %in% colnames(mydata())) | !(input$ycol %in% colnames(mydata())) ) {
return(NULL)
} else{
selected_df <- mydata() %>% select(input$xcol, input$ycol)
plot(selected_df)
}
})
}
shinyApp(ui, server)
I am new to R Shiny. I am attempting to create an app that allows a user to subset a data.frame based on multiple variables and then see the resulting data.
Here is a small example data set:
iter,wave,apples
1,1,600
1,1,500
1,1,400
1,2,300
1,2,200
1,2,100
2,1,1000
2,1,1100
2,1,1200
2,2,1300
2,2,1400
2,2,1500
3,1,1100
3,1,2200
3,1,3300
3,2,4400
3,2,5500
3,2,6600
I would like the user to be able to specify the value of iter and of wave and see the resulting data.
Here is my attempt at the Shiny code. I realize I must be making several silly mistakes.
Edit
Here is my revised code. The end result now comes pretty close to what I want. The sidebar is still not being displayed perfectly.
library(shiny)
setwd('C:/Users/mark_/Documents/simple_RShiny_files/explore')
apple.data <- read.csv('subset_data_based_on_multiple_variables.csv',
header = TRUE, stringsAsFactors = FALSE)
ui <- fluidPage(
titlePanel("Subsetting Apple Dataset"),
sidebarLayout(
sidebarPanel(
uiOutput("codePanel")
),
mainPanel(
tableOutput("view")
)
),
selectInput("codeInput", inputId ="data1", label = "Choose Iter", choices = unique(apple.data$iter)),
selectInput("codeInput", inputId ="data2", label = "Choose Wave", choices = unique(apple.data$wave))
)
server <- function(input, output) {
output$codePanel <- renderUI({
})
dataset <- reactive({
subset(apple.data, (iter == input$data1 & wave == input$data2))
})
output$view <- renderTable(dataset())
}
shinyApp(ui = ui, server = server)
The output
The problem is that both selectInputs have the same inputId. This works:
library(shiny)
apple.data <- data.frame(
iter = c(1L,1L,1L,1L,1L,1L,2L,2L,2L,2L,2L,
2L,3L,3L,3L,3L,3L,3L),
wave = c(1L,1L,1L,2L,2L,2L,1L,1L,1L,2L,2L,
2L,1L,1L,1L,2L,2L,2L),
apples = c(600L,500L,400L,300L,200L,100L,1000L,
1100L,1200L,1300L,1400L,1500L,1100L,2200L,3300L,4400L,
5500L,6600L)
)
ui <- fluidPage(
titlePanel("Subsetting Apple Dataset"),
sidebarLayout(
sidebarPanel(
selectInput("codeInput1", label = "Choose Iter", choices = unique(apple.data$iter)),
selectInput("codeInput2", label = "Choose Wave", choices = unique(apple.data$wave))
),
mainPanel(
tableOutput("view")
)
)
)
server <- function(input, output) {
dataset <- reactive({
return(subset(apple.data, (iter == input$codeInput1 & wave == input$codeInput2)))
})
output$view <- renderTable(dataset())
}
shinyApp(ui = ui, server = server)
i've been trying to interactively zoom in certain parts of a chartSeries with zoomChart and shiny, but can't find the right solution. I would use dateRangeInput or a slider, but i'm not sure how to connect the zoomChart-option from quantmod with shiny. As you might have already assumed, I'm relatively new to shiny and very thankful for your advices!
edit: Data is in the xts-format.
MyCode:
library(quantmod)
library(shiny)
date_range <- as.POSIXct(index(data))
if (interactive()) {
options(device.ask.default = FALSE)
ui <- fluidPage(
titlePanel("Select Range to zoom-in:"),
sidebarLayout(
sidebarPanel(
dateRangeInput("Range", "Choose Date Range:", min=first(date_range),
max=last(date_range), format = "dd-mm-yyyy")
),
mainPanel(
plotOutput("Plot")
)
)
)
server <- function(input, output) {
output$Plot <- renderPlot({
chartSeries(data, type = c("auto", "candlesticks", "matchsticks", "bars","line"),
theme=chartTheme("white"), name=paste(start(data), end(data),sep = " "))
zoomChart(dateRangeInput)
})
}
shinyApp(ui, server)
}
Actually, you were very close. Note the changes in dateRangeInput(): The start and end argument are used instead of min, max. And then you can use the input on the server-side to use zoom-chart.
library(quantmod)
library(shiny)
getSymbols("YHOO")
data <- YHOO
date_range <- index(data)
if (interactive()) {
options(device.ask.default = FALSE)
ui <- fluidPage(
titlePanel("Select Range to zoom-in:"),
sidebarLayout(
sidebarPanel(
dateRangeInput("Range", "Choose Date Range:", start=first(date_range),
end=last(date_range), format = "yyyy-mm-dd")
),
mainPanel(
plotOutput("Plot")
)
)
)
server <- function(input, output) {
output$Plot <- renderPlot({
chartSeries(data, type = c("auto", "candlesticks", "matchsticks", "bars","line"),
theme=chartTheme("white"), name=paste(start(data), end(data),sep = " "))
zoomChart(paste(input$Range, collapse = "::"))
})
observe({
print(input$Range)
})
}
shinyApp(ui, server)
}
As #drmariod indicated It would be beneficial to have a fully reproducible exmaple, which was easy to get in this case via getSymbols().
I am tying to create an R shiny app and I would like to have two selectInput i.e. data set name and column name. Right now, I am able to get data set names in the first Input but I am not able to create dependent column selectIput (whose list will depend upon data set selected). Please guide.
require(shiny)
require(MASS)
a <- data(package = "MASS")[3]
b <- a$results[,3]
ui <- fluidPage(
sidebarPanel(width = 2,
selectInput(inputId = "dsname",label = "Select Dataset:",choices = c(b)),
colnames <- names("dsname"),
selectInput(inputId = "columns", label = "Choose columns",
choices = c(colnames))
)
)
server <- function(input,output) {}
shinyApp(ui <- ui, server <- server)
In order to have "responsive" elements in Shiny, you need to wrap your expressions for computing the responsive elements in reactive({...}).
You could use renderUI in your server() and uiOutput in your ui() with something like this. Here is an example I had built for using some of R's data sets (iris, mtcars, and diamonds):
library(shinythemes)
library(shiny)
library(ggplot2)
ui <- fluidPage(theme = shinytheme("superhero"),
titlePanel("Welcome to Responisve Shiny"),
sidebarLayout(
sidebarPanel(
selectInput("data", "Dataset:",
choices = c("mtcars", "iris", "diamonds")
),
uiOutput("x_axis"),
uiOutput("y_axis"),
uiOutput("color")
),
mainPanel(
plotOutput("distPlot")
)
)
)
server <- function(input, output) {
output$x_axis <- renderUI({
col_opts <- get(input$data)
selectInput("x_axis2", "X-Axis:",
choices = names(col_opts))
})
output$y_axis <- renderUI({
cols2 <- reactive({
col_opts2 <- get(input$data)
names(col_opts2)[!grepl(input$x_axis2, names(col_opts2))]
})
selectInput("y_axis2", "Y-Axis:",
choices = cols2(),
selected = "hp")
})
output$color <- renderUI({
col_opts <- get(input$data)
selectInput("color", "Color:",
choices = names(col_opts),
selected = "cyl")
})
output$distPlot <- renderPlot({
if(input$data == "mtcars"){
p <- ggplot(mtcars, aes_string(input$x_axis2, input$y_axis2, color = input$color)) +
geom_point()
}
if(input$data == "iris"){
p <- ggplot(iris, aes_string(input$x_axis2, input$y_axis2, color = input$color)) +
geom_point()
}
if(input$data == "diamonds"){
p <- ggplot(diamonds, aes_string(input$x_axis2, input$y_axis2, color = input$color)) +
geom_point()
}
print(p)
})
}
shinyApp(ui = ui, server = server)