I am trying to create a shiny app where depending on the dataset, ggvis will create a scatter plot. The app works fine at the beginning. But if I try to change the dataset to mtcars, shiny just disappears.
My ui.R -
library(ggvis)
library(shiny)
th.dat <<- rock
shinyUI(fluidPage(
titlePanel("Reactivity"),
sidebarLayout(
sidebarPanel(
selectInput("dataset", "Choose a dataset:",
choices = c("rock", "mtcars")),
selectInput("xvar", "Choose x", choices = names(th.dat), selected = names(th.dat)[1]),
selectInput("yvar", "Choose y", choices = names(th.dat), selected = names(th.dat)[2]),
selectInput("idvar", "Choose id", choices = names(th.dat), selected = names(th.dat)[3])
),
mainPanel(
ggvisOutput("yup")
)
)
))
server.R -
library(ggvis)
library(shiny)
library(datasets)
shinyServer(function(input, output, session) {
datasetInput <- reactive({
switch(input$dataset,
"rock" = rock,
"mtcars" = mtcars)
})
obs <- observe({
input$dataset
th.dat <<- datasetInput()
s_options <- list()
s_options <- colnames(th.dat)
updateSelectInput(session, "xvar",
choices = s_options,
selected = s_options[[1]]
)
updateSelectInput(session, "yvar",
choices = s_options,
selected = s_options[[2]]
)
updateSelectInput(session, "idvar",
choices = s_options,
selected = s_options[[3]]
)
})
xvarInput <- reactive({
input$dataset
input$xvar
print("inside x reactive," )
print(input$xvar)
xvar <- input$xvar
})
yvarInput <- reactive({
input$dataset
input$yvar
print("inside y reactive,")
print(input$yvar)
yvar <- input$yvar
})
dat <- reactive({
dset <- datasetInput()
xvar <- xvarInput()
# print(xvar)
yvar <- yvarInput()
# print(yvar)
x <- dset[, xvar]
y <- dset[,yvar]
df <- data.frame(x = x, y = y)
})
dat %>%
ggvis(~x, ~y) %>%
layer_points() %>%
bind_shiny("yup")
})
I have tried many ways, but still stuck. Any help will be greatly appreciated.
I left some pointers in the comments but it seems that ggvis evaluates everything quite early so there is a need for some test cases.
rm(list = ls())
library(shiny)
library(ggvis)
ui <- fluidPage(
titlePanel("Reactivity"),
sidebarPanel(
selectInput("dataset", "Choose a dataset:", choices = c("rock", "mtcars")),
uiOutput("xvar2"),uiOutput("yvar2"),uiOutput("idvar2")),
mainPanel(ggvisOutput("yup"))
)
server <- (function(input, output, session) {
dataSource <- reactive({switch(input$dataset,"rock" = rock,"mtcars" = mtcars)})
# Dynamically create the selectInput
output$xvar2 <- renderUI({selectInput("xvar", "Choose x",choices = names(dataSource()), selected = names(dataSource())[1])})
output$yvar2 <- renderUI({selectInput("yvar", "Choose y",choices = names(dataSource()), selected = names(dataSource())[2])})
output$idvar2 <- renderUI({selectInput("idvar", "Choose id",choices = names(dataSource()), selected = names(dataSource())[3])})
my_subset_data <- reactive({
# Here check if the column names correspond to the dataset
if(any(input$xvar %in% names(dataSource())) & any(input$yvar %in% names(dataSource())))
{
df <- subset(dataSource(), select = c(input$xvar, input$yvar))
names(df) <- c("x","y")
return(df)
}
})
observe({
test <- my_subset_data()
# Test for null as ggvis will evaluate this way earlier when the my_subset_data is NULL
if(!is.null(test)){
test %>% ggvis(~x, ~y) %>% layer_points() %>% bind_shiny("yup")
}
})
})
shinyApp(ui = ui, server = server)
Output 1 for rocks
Output 2 for mtcars
Related
I am new in shiny, and maybe it can be easy but I could not make it, so I want to select column name firstly and in second box, it show unique values for selected column, and when choosing any values data table and plot appearing, plot will based on filtered part, thats why it is not hard but my main difficulties to extract interactive filter for data and and in default version, it should be whole data. I share what I have dont it is not working and not correct (this code is without data, I can not share data), I corrected some codes, now I can filter according to one value, but I want to see whole data in default version.
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
pickerInput("eda_col", "Select variable",
choices = c("col 1", "col 2", "col 3", "col 4"), selected = character(0)),
uiOutput("varselect"),
# selectInput("xSelector", label = "Select x axis", choices = xAxischoices),
# selectInput("ySelector", label = "Select the y axis", choices = yAxischoices),
# selectInput("cyLSelector", label = "Select a cylinder", choices = cylinderChoices),
actionButton("RefreshPlot", label = "Refresh")
),
mainPanel(
dataTableOutput("datatable1")
)
)
)
server <- function(input, output) {
output$varselect <- renderUI({
vars <- d[[as.name(input$eda_col)]]
checkboxGroupInput("level_choice", "Select factors to include", unique(vars))
})
# vars_r <- reactive({
# input$vars
# })
#
#
# res_mod <- callModule(
# module = selectizeGroupServer,
# id = "my-filters",
# data = d,
# vars = vars_r
# )
#
# output$table <- DT::renderDataTable({
# req(res_mod())
# res_mod()
# })
filteredData <- reactive({
filteredData <- d %>% filter((!! rlang:: sym(input$eda_col)) == input$level_choice)
return(filteredData)
})
output$datatable1 <- renderDataTable({
datatable(filteredData())
})
}
shinyApp(ui, server)
Please present a full MRE in the future. I have presented your requirements using available dataset gapminder. If this is not your expectation, please update your question using mtcars or gapminder data. Try this
library(gapminder)
choices <- names(gapminder)[1:2]
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
pickerInput("eda_col", "Select variable",
choices = choices, selected = character(0)),
uiOutput("varselect"),
# selectInput("xSelector", label = "Select x axis", choices = xAxischoices),
# selectInput("ySelector", label = "Select the y axis", choices = yAxischoices),
# selectInput("cyLSelector", label = "Select a cylinder", choices = cylinderChoices),
actionButton("RefreshPlot", label = "Refresh")
),
mainPanel(
dataTableOutput("datatable1")
)
)
)
server <- function(input, output) {
output$varselect <- renderUI({
if (is.null(input$eda_col)) vars <- names(gapminder)[1] ## define your default variable selection
else vars <- gapminder[[as.name(input$eda_col)]]
checkboxGroupInput("level_choice", "Select factors to include", unique(vars))
})
# vars_r <- reactive({
# input$vars
# })
#
#
# res_mod <- callModule(
# module = selectizeGroupServer,
# id = "my-filters",
# data = d,
# vars = vars_r
# )
#
# output$table <- DT::renderDataTable({
# req(res_mod())
# res_mod()
# })
filteredData <- reactive({
filteredData <- gapminder %>% filter((!! rlang:: sym(input$eda_col)) %in% input$level_choice)
return(filteredData)
})
output$datatable1 <- renderDataTable({
datatable(filteredData())
})
}
shinyApp(ui, server)
I am trying to show the top ten highest temps from each year but the way I coded it, it will not change and just stays the same.
server.R
library(shiny)
library(dplyr)
library(ggplot2)
library(plotly)
library(readr)
library(tidyverse)
temp_df <-read_csv("~/Environment_Temperature_change_E_All_Data_NOFLAG.csv")
year_df <- temp_df[,8:66] #for the widget
info_df <- temp_df %>%
select(Area, Months, Element)
combine_df <- mutate(info_df, year_df)
combine_df <- na.omit(temp_df) # Get rid of NA rows
combine_df <- temp_df[!grepl("Standard Deviation",temp_df$Element), ] # Get rid of SD rows
top_ten_df <-top_n(combine_df, 10)
# Define server
server <-shinyServer(function(input, output) {
observe({
output$selected_var <- renderText({
paste("You have selected", input$year)
})
output$scatter <- renderPlot({
ggplot(data = top_ten_df, aes(x= Months, y = `Area`)) +
geom_point(aes(col=`Area`))
})
output$data <- renderTable({
final_df <-top_ten_df%>%
select(Area, Months, Element, input$year)
brushedPoints(final_df, input$plot_brush)
})
output$plotlyscatter <- renderPlotly({
plot_ly(data = top_ten_df, x = ~Area, y = ~Months, color=~Area, type = "scatter")
})
})
})
ui.R
library(shiny)
library(dplyr)
library(ggplot2)
library(plotly)
library(readr)
library(tidyverse)
temp_df <-read_csv("~/Environment_Temperature_change_E_All_Data_NOFLAG.csv")
year_df <- temp_df[,8:66] #for the widget
info_df <- temp_df %>%
select(Area, Months, Element)
combine_df <- mutate(info_df, year_df)
# Define UI
ui <- shinyUI(navbarPage(inverse = T, "Rising Temperatures",
tabPanel( "Top Ten Highest Tempratures",
sidebarLayout(
sidebarPanel(
h5("Selection"),
selectInput(inputId = "year",
label = "Select the year:",
choices = names(year_df),
),
textOutput("selected_var"),
),
mainPanel(
plotOutput(outputId = "scatter", brush = "plot_brush"),
tableOutput(outputId = "data"),
plotlyOutput(outputId = "plotlyscatter")
)
)
)
)
)
Also, I do not know where to use the app.R in this situation, sorry I am a bit new to all of this. I would like this to be an interactive scatter plot that when you pick an input from the widget.
I have a fully functioning shiny app for performing regression analysis, with summary(), tidy(), and augment().
However, I would like to add a filter selection in the shiny for the uploaded data.
My dataset is quite big and within the dataset, it is divided into 5 types, (so, type_1, type_2, type_3, etc). Right now I have to divide my dataset manually outside the shiny app to 5 different datasets so I can only run the regression for one specific type at a time.
It would be great to be able to choose and select the type within the shiny, without going through all this hassle.
Grateful for all your help.
library(shiny)
library(shinyWidgets)
library(DT)
library(dplyr)
library(nlme)
library(broom)
ui <- navbarPage("dd",
tabPanel("Reg",
sidebarPanel(
fileInput(
inputId = "filedata",
label = "Upload data. csv",
multiple = FALSE,
accept = c(".csv"),
buttonLabel = "Choosing ...",
placeholder = "No files selected yet"
),
uiOutput("xvariable"),
uiOutput("yvariable")
),
mainPanel(
DTOutput("tb1"),
fluidRow(
column(6, verbatimTextOutput('lmSummary')),
column(6,verbatimTextOutput("tid")),
column(6,verbatimTextOutput("aug"))
)
)
)
)
server <- function(input, output, session) {
data_1 <- reactive({
req(input$filedata)
inData <- input$filedata
if (is.null(inData)){ return(NULL) }
mydata <- read.csv(inData$datapath, header = TRUE, sep=",")
})
output$tb1 <- renderDT(head(data_1()))
output$xvariable <- renderUI({
req(data_1())
xa<-colnames(data_1())
pickerInput(inputId = 'xvar',
label = 'Select x-axis variable',
choices = c(xa[1:length(xa)]), selected=xa[2],
options = list(`style` = "btn-info"),
multiple = TRUE)
})
output$yvariable <- renderUI({
req(data_1())
ya<-colnames(data_1())
pickerInput(inputId = 'yvar',
label = 'Select y-axis variable',
choices = c(ya[1:length(ya)]), selected=ya[1],
options = list(`style` = "btn-info"),
multiple = FALSE)
})
lmModel <- reactive({
req(data_1(),input$xvar,input$yvar)
x <- as.numeric(data_1()[[as.name(input$xvar)]])
y <- as.numeric(data_1()[[as.name(input$yvar)]])
current_formula <- paste0(input$yvar, " ~ ", paste0(input$xvar, collapse = " + "))
current_formula <- as.formula(current_formula)
model <- lm(current_formula, data = data_1(), na.action=na.exclude)
return(model)
})
output$lmSummary <- renderPrint({
req(lmModel())
summary(lmModel())
})
output$tid <- renderPrint({
req(lmModel())
tidy(lmModel())
})
output$aug <- renderPrint({
req(lmModel())
augment(lmModel())
})
}
shinyApp(ui, server)
How the uploaded dataset could look like, for better explanation
data_set <- data.frame (Simulation_1 = c(1,2,3,4,5,6,7,8,9,10),
Simulation_2 = c(1,2,3,4,5,6,7,8,9,10),
Simulation_3 = c(1,2,3,4,5,6,7,8,9,10),
type = c("type_1", "type_2", "Type_5",
"type_1", "type_2", "Type_3",
"type_1", "type_2", "Type_1","Type_4")
)
Perhaps you are looking for this
library(shiny)
library(shinyWidgets)
library(DT)
library(dplyr)
library(nlme)
library(broom)
data_set <- data.frame (Simulation_1 = c(1,2,3,4,5,6,7,8,9,10),
Simulation_2 = c(1,2,3,4,5,6,7,8,9,10),
Simulation_3 = c(1,2,3,4,5,6,7,8,9,10),
type = c("type_1", "type_2", "Type_5",
"type_1", "type_2", "Type_3",
"type_1", "type_2", "Type_1","Type_4")
)
ui <- navbarPage("dd",
tabPanel("Reg",
sidebarPanel(
fileInput(
inputId = "filedata",
label = "Upload data. csv",
multiple = FALSE,
accept = c(".csv"),
buttonLabel = "Choosing ...",
placeholder = "No files selected yet"
),
uiOutput("col"),
uiOutput("type"),
uiOutput("xvariable"),
uiOutput("yvariable")
),
mainPanel(
DTOutput("tb1"),
fluidRow(
column(6, verbatimTextOutput('lmSummary')),
column(6,verbatimTextOutput("tid")),
column(6,verbatimTextOutput("aug"))
)
)
)
)
server <- function(input, output, session) {
data_0 <- reactive({
# req(input$filedata)
# inData <- input$filedata
# if (is.null(inData)){ return(NULL) }
# mydata <- read.csv(inData$datapath, header = TRUE, sep=",")
data_set
})
output$tb1 <- renderDT(head(data_1()))
output$col <- renderUI({
req(data_0())
selected = colnames(data_0())[length(colnames(data_0()))]
selectInput("mycol", "Choose column", choices = colnames(data_0()), selected = selected)
})
output$type <- renderUI({
req(data_0(),input$mycol)
selectInput("mytype", "Choose Type", choices = unique(data_0()[[input$mycol]]))
})
data_1 <- eventReactive(input$mytype, {
req(data_0(),input$mycol,input$mytype)
df <- data_0()
df$newvar <- df[[input$mycol]]
df %>% dplyr::filter(newvar %in% input$mytype) %>% dplyr::select(- c(newvar))
})
output$xvariable <- renderUI({
req(data_1())
xa<-colnames(data_1())
pickerInput(inputId = 'xvar',
label = 'Select x-axis variable',
choices = c(xa[1:length(xa)]), selected=xa[2],
options = list(`style` = "btn-info"),
multiple = TRUE)
})
output$yvariable <- renderUI({
req(data_1())
ya<-colnames(data_1())
pickerInput(inputId = 'yvar',
label = 'Select y-axis variable',
choices = c(ya[1:length(ya)]), selected=ya[1],
options = list(`style` = "btn-info"),
multiple = FALSE)
})
lmModel <- reactive({
req(data_1(),input$xvar,input$yvar)
x <- as.numeric(data_1()[[as.name(input$xvar)]])
y <- as.numeric(data_1()[[as.name(input$yvar)]])
current_formula <- paste0(input$yvar, " ~ ", paste0(input$xvar, collapse = " + "))
current_formula <- as.formula(current_formula)
model <- lm(current_formula, data = data_1(), na.action=na.exclude)
return(model)
})
output$lmSummary <- renderPrint({
req(lmModel())
summary(lmModel())
})
output$tid <- renderPrint({
req(lmModel())
tidy(lmModel())
})
output$aug <- renderPrint({
req(lmModel())
augment(lmModel())
})
}
shinyApp(ui, server)
\
I'm a really beginner in R Shiny.
I have a similar problem as at the link below.
multiple group_by in shiny app
Instead of making a table which worked out/I managed by following the instructions in the link above.
I would like to make a plot, preferably with hchart. In which i would to switch the information because of the group by. The difficult part / or the thing that doesn't work is putting the group_by on the x-axis.
## hier de tabel versie
df2 <- readRDS("Data.rds")
library(shiny)
library(DT)
library(dplyr)
ui <- fluidPage(
titlePanel("Dashboard"),
sidebarLayout(
sidebarPanel(
uiOutput("groups")
),
mainPanel(
DT::dataTableOutput("summary")
)
)
)
server <- function(input, output) {
mydata <- reactive({
data <- df2
data
})
output$groups <- renderUI({
df <- mydata()
selectInput(inputId = "grouper", label = "Group variable", choices = c("L","Lt","Lp"), selected = "L")
})
summary_data <- reactive({
req(input$grouper)
mydata() %>%
dplyr::group_by(!!!rlang::syms(input$grouper)) %>%
dplyr::summarise(aantal = n()) %>%
dplyr::arrange(desc(aantal))
})
output$summary <- DT::renderDataTable({
DT::datatable(summary_data())
})
}
shinyApp(ui, server)
The above code works, but i tried to make a plot like this:
df2 <- readRDS("Data.rds")
library(shiny)
library(highcharter)
library(dplyr)
ui <- fluidPage(
titlePanel("Dashboard"),
sidebarLayout(
sidebarPanel(
uiOutput("groups")
),
mainPanel(
highchartOutput("plotje")
)
)
)
server <- function(input, output) {
mydata <- reactive({
data <- df2
data
})
output$groups <- renderUI({
df <- mydata()
selectInput(inputId = "grouper", label = "Group variable", choices = c("L","Lt","Lp"), selected = "L")
})
summary_data <- reactive({
req(input$grouper)
mydata() %>%
dplyr::group_by(!!!rlang::syms(input$grouper)) %>%
dplyr::summarise(aantal = n()) %>%
dplyr::arrange(desc(aantal))
})
output$plotje <- renderHighchart({
data <- summary_data()
hchart(data, "column", hcaes(x = "grouper" , y = aantal)) # --> de plot zelf komt in het output deel van de UI
})
}
shinyApp(ui, server)
Could someone help me out?!
Thanks in advance!
Kind regards,
Steffie
You have the grouper column in the input$grouper var.
It's just a matter of unquoting it.
The line hchart(data, "column", hcaes(x = "grouper" , y = aantal)) should be:
hchart(data, "column", hcaes(x = !!input$grouper , y = aantal))
Full example (with iris data as you didn't provide an example of your own data):
library(shiny)
library(DT)
library(highcharter)
library(dplyr)
ui <- fluidPage(titlePanel("Dashboard"),
sidebarLayout(
sidebarPanel(uiOutput("groups")),
mainPanel(DT::dataTableOutput("summary"),
highchartOutput("plot"))
))
server <- function(input, output) {
mydata <- reactive({
iris
})
output$groups <- renderUI({
df <- mydata()
selectInput(
inputId = "grouper",
label = "Group variable",
choices = c("Petal.Length", "Species"),
selected = "Species"
)
})
summary_data <- reactive({
req(input$grouper)
mydata() %>%
dplyr::group_by(!!!rlang::syms(input$grouper)) %>%
dplyr::summarise(aantal = n()) %>%
dplyr::arrange(desc(aantal))
})
output$summary <- DT::renderDataTable({
DT::datatable(summary_data())
})
output$plot <- renderHighchart({
req(input$grouper)
data <- summary_data()
hchart(data, "column", hcaes(x = !!input$grouper, y = aantal))
})
}
shinyApp(ui, server)
I have one problem with create dynamic UI (selectInput). I mean, I have two dataframes and one selectInput button which should change number of output (column name) depending on dataframe which I choose.
I just get error: Error: == only defined for equally-sized data frames when I choose df2 dataframe. Could anyone tell me what I do wrong? This is my if function:
output$xvars <- renderUI({
if (datasetInput() == df1){
axis_vars_x <- colnames(df1[c(1,2)])
selectInput("xvar", "X-axis variable", axis_vars_x, selected = "id")
}
else{
axis_vars_x <- colnames(df2[1])
selectInput("xvar", "X-axis variable", axis_vars_x, selected = "id")
}
})
ui.R
library(dplyr)
library(shiny)
library(ggvis)
shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
radioButtons("dataset", label = h4("Product level"),
choices = list("Item" = "df1", "Task" = "df2")),
uiOutput("xvars"),
),
mainPanel(
ggvisOutput("plot")
)
)
))
server.R
library(shiny)
library(dplyr)
df1 <- data.frame(id = c(1,2,3,4,5), number = c(20,30,23,25,34), ds = c(1,2,3,42,2))
df2 <- data.frame(id = c(1,2), number = c(33,40), ds = c(1,2))
shinyServer(function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
df1 = df1,
df2 = df2)
})
output$xvars <- renderUI({
if (datasetInput() == df1){
axis_vars_x <- colnames(df1[c(1,2)])
selectInput("xvar", "X-axis variable", axis_vars_x, selected = "id")
}
else{
axis_vars_x <- colnames(df2[1])
selectInput("xvar", "X-axis variable", axis_vars_x, selected = "id")
}
})
data <- reactive({
df <- datasetInput()
})
vis <- reactive({
data %>%
ggvis(~id, ~number) %>%
layer_points(fill = ~factor(id)) %>%
scale_nominal("fill", range = c("red","blue","green","yellow","black"))
})
vis %>% bind_shiny("plot")
})
From you comments, I assumed you wanted to change the y-axis to whatever was selected in the selectInput boxes. To do this with ggvis you need to change the data you pass to the plot.
You can try the following code, I changed a few of your variables:
server.R
library(shiny)
library(dplyr)
df1 <- data.frame(id = c(1,2,3,4,5), number = c(20,30,23,25,34), ds = c(1,2,3,42,2))
df2 <- data.frame(id = c(1,2), number = c(33,40), ds = c(1,2))
shinyServer(function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
"df1" = df1,
"df2" = df2)
})
output$yvars <- renderUI({
if (identical(df1,datasetInput())){
axis_vars_y <- colnames(df1[-1])
selectInput("yvar", "X-axis variable", axis_vars_y, selected = "id")
}
else{
axis_vars_y <- colnames(df2[-1])
selectInput("yvar", "X-axis variable", axis_vars_y, selected = "id")
}
})
yVarName<-reactive({
yValue<-"number"
if(!is.null(input$yvar)){
yValue<-input$yvar
}
yValue
})
data <- reactive({
df<-datasetInput()
yValue<-"number"
if(!is.null(input$yvar)){
yValue<-input$yvar
}
df <- datasetInput()[,c("id",yValue)]
names(df)<-c("id","yVar")
df
})
vis <- reactive({
data %>%
ggvis(~id, ~yVar) %>%
layer_points(fill = ~factor(id)) %>%
scale_nominal("fill", range = c("red","blue","green","yellow","black")) %>%
add_axis("y", title = yVarName())
})
vis %>% bind_shiny("plot")
})
ui.R
library(dplyr)
library(shiny)
library(ggvis)
shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
radioButtons("dataset", label = h4("Product level"),
choices = list("Item" = "df1", "Task" = "df2")),
uiOutput("yvars")
),
mainPanel(
ggvisOutput("plot")
)
)
))