I have a application that has a reative table(based on 2 selectInputs) and a graph. The data for graph is taken from reactive table.
So both graph and table is using the same data. So while constructing a graph, can I observe what the table is having.
Or should I read the same table again in the graph?
I mean should we call head(iris,n = as.numeric(input$rows)) again twice below?
Example,
library(shiny)
library(DT)
library(rAmCharts)
ui <- fluidPage(
selectInput("rows","Rows",c(1:150)),
dataTableOutput("input_table"),
amChartsOutput("barplot",width = 750, height = 500)
)
server <- function(input, output, session) {
output$input_table <- renderDataTable({
new_iris <- head(iris,n = as.numeric(input$rows))
datatable(new_iris)
})
output$barplot <- renderAmCharts({
new_iris1 <- head(iris,n = as.numeric(input$rows)) ## should i call this again???????? Cannot we use from rendertable?
new_iris1 <- new_iris1 %>% group_by(Species) %>% summarise(total = sum(Petal.Length))
pipeR::pipeline(
amBarplot(
x = "Species",
y = "total",
ylab = "X",
xlab = "Y",
data = new_iris1,
labelRotation = 90
),
setChartCursor()
)
})
}
shinyApp(ui, server)
You may want to put your data object in a reactive expression so you can see what is being rendered, like so, this way you can access data() later on in your app
library(shiny)
library(DT)
library(dplyr)
library(rAmCharts)
ui <- fluidPage(
selectInput("rows","Rows",c(1:150)),
dataTableOutput("input_table"),
amChartsOutput("barplot",width = 750, height = 500)
)
server <- function(input, output, session) {
data <- eventReactive(input$rows,{
head(iris,n = as.numeric(input$rows))
})
output$input_table <- renderDataTable({
datatable(data())
})
output$barplot <- renderAmCharts({
new_iris1 <- data()
new_iris1 <- new_iris1 %>% group_by(Species) %>% summarise(total = sum(Petal.Length))
pipeR::pipeline(
amBarplot(
x = "Species",
y = "total",
ylab = "X",
xlab = "Y",
data = new_iris1,
labelRotation = 90
),
setChartCursor()
)
})
}
shinyApp(ui, server)
Related
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 larger application where i need to identify data clusters.
For this I would like to create a pair plot and use the brush option to mark some points. These marked points are later used in another part of the program.
The problem is that i can not specify the xvar and yvar parameters for the pair plot.
At the moment i have no idea how to solve this.
Is there someone around who had the same problem?
I tried to create a simple application that demonstrates the problem.
Finally i need the IMG_Selected_Tiles variable to mark specific parts of a source image...
Thanks for any help
Jan
IMG_SelectedTiles <- reactiveValues ()
IMG_Statistics <- reactiveValues ()
library ("ggplot2")
shinyApp(
ui = basicPage(
fluidRow(
column(width = 4,
plotOutput("plot", height=300,
click = "plot_click", # Equiv, to click=clickOpts(id="plot_click")
hover = hoverOpts(id = "plot_hover", delayType = "throttle"),
brush = brushOpts(id = "plot_brush")
),
h4("Clicked points"),
tableOutput("plot_clickedpoints"),
h4("Brushed points"),
tableOutput("plot_brushedpoints")
),
column(width = 4,
verbatimTextOutput("plot_clickinfo"),
verbatimTextOutput("plot_hoverinfo")
),
column(width = 4,
wellPanel(actionButton("newplot", "New plot")),
verbatimTextOutput("plot_brushinfo"),
verbatimTextOutput("text_IMG_selected_tiles")
)
)
),
server = function(input, output, session) {
IMG_Statistics$data <- reactive({
input$newplot
iris
})
output$plot <- renderPlot({
d <- IMG_Statistics$data ()
ggpairs (d)
#plot(d$speed, d$dist)
})
output$plot_clickinfo <- renderPrint({
cat("Click:\n")
str(input$plot_click)
})
output$plot_hoverinfo <- renderPrint({
cat("Hover (throttled):\n")
str(input$plot_hover)
})
output$plot_brushinfo <- renderPrint({
cat("Brush (debounced):\n")
str(input$plot_brush)
})
output$plot_clickedpoints <- renderTable({
# For base graphics, we need to specify columns, though for ggplot2,
# it's usually not necessary.
res <- nearPoints(IMG_Statistics$data(),
input$plot_click,
"speed",
"dist")
if (nrow(res) == 0) return()
res
})
output$plot_brushedpoints <- renderTable({
res <- brushedPoints(IMG_Statistics$data(), input$plot_brush, allRows = TRUE)
if (nrow (res) == 0) return()
#just as an example data are taken from another data structure
IMG_SelectedTiles <- cbind(IMG_Statistics$data [res_selected_, 1],
IMG_Statistics$data [res_selected_, 2],
IMG_Statistics$data [res_selected_, 3])
})
output$text_IMG_selected_Tiles <-renderTable ({
cat ("Selected data:\n")
str (IMG_Selected_Tiles())
})
}
)
Maybe with the help of plotly?
library(plotly)
library(GGally)
library(shiny)
ui <- fluidPage(
plotlyOutput("myPlot"),
)
server <- function(input, output, session){
output$myPlot = renderPlotly({
highlight_key(iris) %>%
GGally::ggpairs(aes(color = Species), columns = 1:4) %>%
ggplotly() %>%
highlight("plotly_selected") %>%
layout(dragmode = "select") %>%
event_register(event = "plotly_brushed") %>%
event_register(event = "plotly_selected")
})
observeEvent(event_data("plotly_brushed"), {
cat("Selected box:\n")
print(event_data("plotly_brushed"))
# alternative method
#xmin <- event_data("plotly_brushed")$x[1]
#xmax <- event_data("plotly_brushed")$x[2]
#ymin <- event_data("plotly_brushed")$y[1]
#ymax <- event_data("plotly_brushed")$y[2]
})
observeEvent(event_data("plotly_selected"), {
cat("Selected points:\n")
print(event_data("plotly_selected"))
})
}
shinyApp(ui, server)
Thanks for your help, Stéphane!
I finally made a solution for the problem, using your approach in a very similar way.
I think, that this is a little tricky problem. Thus, I prepared some sample code. It is not the most elegant sample, but it may help some others facing a similar problem...
Jan
library ("plotly")
IMG_SelectedTiles <- reactiveValues ()
IMG_Statistics <- reactiveValues ()
IMG_selected_keys <- reactiveValues ()
IMG_selected_points <- reactiveValues ()
ui <- fluidPage(
wellPanel(actionButton("newplot", "New plot")),
plotlyOutput("myPlot"),
h4 ("Selected points"),
tableOutput("selected_points"),
h4 ("Selected keys"),
tableOutput("selected_keys"),
h4 ("Selected data"),
tableOutput("selected_data")
)
server <- function(input, output, session){
# get arbitrary data into my reactive variable
IMG_Statistics$data <- reactive({
input$newplot
iris
})
output$myPlot = renderPlotly({
#height = "1500px"
#width = "1500px",
highlight_key(IMG_Statistics$data() ) %>%
GGally::ggpairs () %>%#(aes(color = "black"), columns = 1:4) %>%
ggplotly() %>%
highlight("plotly_selected") %>%
layout(dragmode = "select", autosize = FALSE, height = 1500, width = 1500) %>%
# event_register(event = "plotly_brushed") %>%
event_register(event = "plotly_selected")
})
observeEvent(event_data("plotly_brushed"), {
# cat("Selected brush:\n")
# print (str (event_data("plotly_brushed")))
# alternative method
#xmin <- event_data("plotly_brushed")$x[1]
#xmax <- event_data("plotly_brushed")$x[2]
#ymin <- event_data("plotly_brushed")$y[1]
#ymax <- event_data("plotly_brushed")$y[2]
})
observeEvent(event_data("plotly_selected"), {
cat("Data:\n")
print (str (IMG_Statistics$data))
IMG_selected_keys$data <- event_data("plotly_selected")$key
cat("Selected keys:\n")
print ( IMG_selected_keys$data)
IMG_selected_points$data <- event_data("plotly_selected")$pointNumber
cat("Selected point numbers:\n")
print (IMG_selected_points$data)
IMG_SelectedTiles$data <- IMG_Statistics$data () [as.numeric (event_data ("plotly_selected")$key), ]
cat("Selected tiles:\n")
print (IMG_SelectedTiles$data)
})
output$selected_keys <- renderPrint ({IMG_selected_keys$data })
output$selected_points <- renderPrint ({IMG_selected_points$data})
output$selected_data <- renderTable({
IMG_SelectedTiles$data
})
}
shinyApp(ui, server)
I keep getting errors like Error in : object of type 'closure' is not subsettable or
'..1'. x Input '..1' must be of size 28 or 1, not size 0. I am trying to change the bar graph based on what options are selected or not in the checkbox.
I changed the column names for ease of use from where I got the data.
library(shiny)
library(dplyr)
library(plotly)
#dataset link: https://www.kaggle.com/mahirahmzh/starbucks-customer-retention-malaysia-survey?select=Starbucks+satisfactory+survey.csv
#c("Timestamp","Gender","age","currently","income","visit_freq","Enjoy","Time","Nearby","membership","freq_purchase","avg_spend","Ratevsother","rateprice","salesandpromotion","ambiance","wifi","service","meetup","heardaboutpromotions","continuepatronage")
data <-read.csv("Starbucks satisfactory survey.csv", header=TRUE)
Categorical.Variables <- c("visit_freq", "age", "income")
ui <- fluidPage(
sidebarPanel(
selectInput('category', choices = Categorical.Variables, label = 'Select filter options:'),
conditionalPanel(condition = "input.category != '-'",
uiOutput("select_category"))
)
)
server <- function(input, output) {
output$select_category <- renderUI({
choices <- as.list(unique(data[[input$category]]))
checkboxGroupInput('categorycheck', label = 'Select filter:',
choices = choices,selected = choices)
data2 <- reactive({
data %>%
group_by(gender,data[[input$category]], currently,membership) %>%
summarize(n = n(), .groups="drop") %>%
filter(data[[input$category]] %in% input$categorycheck) %>%
filter(membership == "Yes")})
renderPlotly({
data2 <- data2()
colnames(data2) <- c("gender","filtercategory","currently","membership","n")
plot_ly(data2, x = ~currently, y = ~n, type = "bar", color=~gender, colors="Dark2") %>%
layout(barmode = 'group')
})
})
}
shinyApp(ui, server)
You have several issues. You should close your renderUI prior to using input$categorycheck in the reactive object data2. In addition, columns names in the csv file are long. Once you define the column names of data the way you are analyzing, it will work. Try this
mydata <-read.csv("Starbucks satisfactory survey.csv", header=TRUE)
names(mydata)[1:10] <- c("Timestamp", "gender", "Age", "currently", "Income", "visit_freq","drink_freq","time_spent", "nearby","membership")
Categorical.Variables <- c("Age", "Income", "visit_freq")
ui <- fluidPage(
sidebarPanel(
selectInput('category', choices = Categorical.Variables, label = 'Select filter options:'),
#conditionalPanel(condition = "input.category != '-'",
uiOutput("select_category")
# )
),
mainPanel(plotlyOutput("myplot"),
DTOutput("t1")
)
)
server <- function(input, output) {
output$select_category <- renderUI({
req(input$category)
choices <- as.list(unique(mydata[[input$category]]))
checkboxGroupInput('categorycheck', label = 'Select filter:',
choices = choices,selected = choices)
})
data2 <- reactive({
req(input$category,input$categorycheck)
mydata %>%
group_by(gender,.data[[input$category]], currently,membership) %>%
dplyr::summarize(n = n(), .groups="drop") %>%
filter(.data[[input$category]] %in% input$categorycheck) %>%
filter(membership == "Yes")})
output$t1 <- renderDT(data2())
output$myplot <- renderPlotly({
req(data2())
data2 <- data2()
colnames(data2) <- c("gender","filtercategory","currently","membership","n")
plot_ly(data2, x = ~currently, y = ~n, type = "bar", color=~gender, colors="Dark2") %>%
layout(barmode = 'group')
})
}
shinyApp(ui, server)
I have a shiny application where the filters here are reactive with respect to each other. Not sure there is some issue in the code. The values are not to be seen here. Can anyone help me here?
Is there any alternate way?
library(shiny)
library(readxl)
library(dplyr)
library(shinyWidgets) ## for picker input
library(shinydashboard)
library(DT)
library(tidyverse)
library(xtable)
library(shinycssloaders)
library(plotly)
library(htmlwidgets)
library(sparkline)
library(data.table)
require(reshape2)
library(glue)
data_13_Sam <- data.frame(
Ratings = c(1,2,3,4,5,1,2,3,4,5), flag = c("Yes","No","Yes","No","Yes","No","Yes","No","Yes","Yes")
)
ui <- fluidPage(
column(offset = 0, width = 1,uiOutput("rat")),
column(offset = 0, width = 2, uiOutput("nt"))
)
server <- function(input, output, session) {
filter_data <- reactive({
data_13_Sam %>% filter(flag %in% input$nt, Ratings %in% input$rat)
})
##### nt
output$nt <- renderUI({
selectInput("nt",label = tags$h4("New"),choices = unique(filter_data()$flag))
})
###### rat
output$rat <- renderUI({
selectInput("rat",label = tags$h4("Rat"),choices = unique(filter_data()$Ratings))
})
}
shinyApp(ui, server)
I also tried with this second approach as well . But did not work. Writing to csv file and then pulling from that
library(shiny)
library(readr)
library(dplyr)
data_13_Sam <- data.frame(
Ratings = c(1,2,3,4,5,1,2,3,4,5), flag = c("Yes","No","Yes","No","Yes","No","Yes","No","Yes","Yes"),
fle = c("All","All","All","All","All","All","All","All","All","All")
)
ui <- fluidPage(
column(offset = 0, width = 1,uiOutput("all")),
column(offset = 0, width = 1,uiOutput("rat")),
column(offset = 0, width = 2, uiOutput("nt")),
tableOutput('data')
)
server <- function(input, output, session) {
observeEvent(input$rat,{
grp_by <- data_13_Sam %>% filter(Ratings %in% input$rat) %>% group_by(flag) %>% summarise(Det= n())
write.csv(grp_by,"grp_by.csv")
})
observeEvent(input$nt,{
grp_by_nt <- data_13_Sam %>% filter(flag %in% input$nt) %>% group_by(Ratings) %>% summarise(Det= n())
write.csv(grp_by_nt,"grp_by_nt.csv")
})
output$rat <- renderUI({
if(!is.null(input$nt)){grp_by_nt_read <- read_csv("grp_by_nt.csv")}
selectInput("rat",label = tags$h4("Rat"),choices = unique(grp_by_nt_read$Ratings))
})
output$nt <- renderUI({
if(!is.null(input$rat)){grp_by_read <- read_csv("grp_by.csv")}
selectInput("nt",label = tags$h4("New"),choices = unique(grp_by_read$flag))
})
}
shinyApp(ui, server)
You have created a circular dependency. A needs B, B needs C but C needs A. So it is not able to complete anything.
You can try this -
library(shiny)
data_13_Sam <- data.frame(
Ratings = c(1,2,3,4,5,1,2,3,4,5), flag = c("Yes","No","Yes","No","Yes","No","Yes","No","Yes","No")
)
ui <- fluidPage(
column(offset = 0, width = 1,uiOutput("rat")),
column(offset = 0, width = 2, uiOutput("nt")),
tableOutput('data')
)
server <- function(input, output, session) {
filter_data <- reactive({
data_13_Sam %>% filter(flag %in% input$nt, Ratings %in% input$rat)
})
output$rat <- renderUI({
selectInput("rat",label = tags$h4("Rat"),choices = unique(data_13_Sam$Ratings))
})
output$nt <- renderUI({
req(input$rat)
selectInput("nt",label = tags$h4("New"),choices = unique(data_13_Sam$flag[data_13_Sam$Ratings == input$rat]))
})
output$data <- renderTable({filter_data()})
}
shinyApp(ui, server)
So rat displays all the ratings and only for those ratings we display the nt values. You can also reverse this condition if needed to show all values of nt and based on it's selection show rat values.
\
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)