Im trying to create a dataframe which will update its values based on the shiny widgets selections in the sidebar. But the datatable I use to check this does not seem to display all column names and cell values .
library(shiny)
library(dplyr)
library(shinydashboard)
library(DT)
### user inter phase
ui <- fluidPage(
### App title ----
titlePanel(title=div(img(src="pics/IRP_NHSc.jpg", width="99%")))
,
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
### Input files ----
selectInput("Price","Select the price for analysis", c("List price","End consumer price without VAT", "End consumer price with VAT", "Reimbursed price"),multiple = T),
selectInput("IRP_A","Select IRP formula", c("Price average"="PA","Median price"="MP","3 lowest price average"="3L", "Lowest price"="LP", "Turkish rule"="TR", "Swiss rule"="SR" )),
# Input: Slider for the number of bins ----
sliderInput(inputId = "increase",
label = "% increase",
min = -20,
max = 100,
value = 35), width = 2,
),
### Main panel for displaying outputs ----
mainPanel(
tabsetPanel(
tabPanel("Export report",
dataTableOutput("tab7"))
)
)
)
)
#### Server
server <- function(input, output, session) {
output$tab7<-renderDataTable({
Price<-input$Price
IRP<-input$IRP_A
Per<-input$increase
df<-as.data.frame(Price,IRP,Per)
})
}
shinyApp(ui = ui, server = server)
I'm not really sure what you want to see but I think as.data.frame is taking only the first object as the thing to convert into a data frame and the second as the row name. If you put them in a list you can see all the inputs in the table:
df<-as.data.frame(list('price' = Price, 'irp' = IRP,'per' = Per))
(although it does give an error until you select at least one price)
Related
[picture of my code and shiny app][1]I am trying to write a shiny app where I have two drop down menus and I create two histograms from those dropdowns and a salary variable I have stored in a dataframe. I can create the drop downs but I am lost on how to save the selection and use the selection as a independent variable for my model. any help at all would be huge.
I tried using a save button to save the selection from the drop down but I couldn't get that to store the variable in a way that I could verify with my dataframe.
code below
library(dplyr)
library(ggplot2)
library(shiny)
data <- read.csv("C:/Users/lewis/OneDrive/Desktop/STA 580( R
programming)/Final_Project/salaries_entry.csv")
data
wxdata <- data.frame(
Remote = c("0%", "50%", "100%"),
Size = c("Small","Medium","Large")
)
remotelist <- unique(wxdata$Remote)
sizelist <- unique(wxdata$Size)
ui <- fluidPage(
titlePanel("Data Science / Data Engineer Salaries"),
sidebarLayout(
sidebarPanel(),
mainPanel(
h4("The purpose of this app is to give you an idea"),
h4("about the potential money you could be making as an"),
h4("entry level employee in the Data Science field based "),
h4("on a few key factors. Test it out and Get that BAG!")
)
),
inputPanel(
selectInput(
"RemoteWork",
label = "Select Amount of Remote Work",
choices = remotelist
)
),
inputPanel(
selectInput(
"CompanySize",
label = "Select the Size of the Company",
choices = sizelist
)
),
)
server <- function(input, output) {
output$minplot <- renderPlot(draw_plot(input$PlotCity))
}
shinyApp(ui = ui, server = server)
I'm trying to learn R and am running into issues using the Shiny dashboard GUI. I'm trying to turn these SelectInputs
tabItem(tabName = "data",
fluidRow(
selectInput("Telecommuting", "Telecommute (Yes=1, No=0)", c("1","0")),
selectInput("logo", "Has Logo(Yes=1, No=0)", c("1","0")),
selectInput("questions", "Has Questions(Yes=1, No=0)", c("1","0")),
into dataframe inputs that I call at the top of my dashboard script
dfTemp<- read.csv('words.csv', header=T)
The CSV is just a one row csv with all values initialized to 0. I want to take the SelectInputs by the user and place them into the dataframe according to the input.
storeCommute<- renderText(input$Telecommuting)
dfTemp$telecommuting<- storeCommute
However when I try to set the dfTemp$telecommuting to the storeCommute input, I get an error:
Error in xj[i] : object of type 'closure' is not subsettable
I have searched for hours and there is no info on how to get this done. Any help would be awesome, thanks!
What you describe is doable yet quite complicated due to the nature of selectInput. Below is an example which I think would very close to what you write and the example include various usage of different input ui, reactive values, and event handling in Shiny.
library(shiny)
library(dplyr)
# ui part
ui <- fluidPage(
# Application title
titlePanel("Trial Input added rows to a dataframe"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
fluidRow(
# a text input for input random word
textInput(inputId = "word",
label = 'Word', width = "300px")
),
fluidRow(
# a checkbox for Yes/No values - telecommute
checkboxInput(inputId = "telecommute",
label = 'Telecommuting',
value = FALSE)
),
fluidRow(
# a checkbox for Yes/No values - logo
checkboxInput(inputId = "logo",
label = 'Has Logo',
value = FALSE)
),
fluidRow(
# a checkbox for Yes/No values - questions
checkboxInput(inputId = "questions",
label = 'Has Questions',
value = FALSE)
),
fluidRow(
# Action button that added rows to the reactive value df on click
actionButton(inputId = "add_rows", label = "Add rows")
)
),
# Show a plot of the generated distribution
mainPanel(
fluidRow(
# data.frame output - will change follow each "add_rows" click
tableOutput(outputId = "data_table")
),
fluidRow(
# Action button that save the current data to words.csv
actionButton(inputId = "save_csv", label = "Save to csv")
)
)
)
)
# server part
server <- function(input, output) {
# reactive values that store df_temp for later processing & visualization
values <- reactiveValues(
df_temp =
{
# for the first time running if no words.csv available
# an empty tibble is created.
data <- tibble(word = character(0),
telecommute = logical(0),
logo = logical(0),
questions = logical(0))
if (file.exists("./words.csv")) {
# if words.csv exist load the data from csv file
data <- read.csv("./words.csv", stringsAsFactors = FALSE)
}
data
}
)
# server code handling logic added row to values$df_temp
observeEvent(input$add_rows, {
values$df_temp <- bind_rows(values$df_temp,
tibble(word = input$word,
telecommute = input$telecommute,
logo = input$logo,
questions = input$questions))
})
# render the values$df_temp to a table output to UI
output$data_table <- renderTable(values$df_temp)
# server code handling logic to save values$df_temp when click "Save to csv"
observeEvent(input$save_csv, {
write.csv(values$df_temp, "./words.csv", row.names = FALSE)
})
}
# Run the application
shinyApp(ui = ui, server = server)
I'm hoping to display a reactive datatable for my Shiny app. I'm using renderDataTable() and have made sure that the data table is returned in the reactive function. I've noticed that the datatable renders fine outside of the Shiny App, so not a variable/computation error. The reason I'm hoping to use a datatable in the first place is so that I can display cleaned up column names and display the dataframe in a more clean manner. Please let me know what else I can try, or if I should change my approach.
Here is the server code:
server <- function(input, output) {
dataset <- reactive({
shiny_tuition_salary <- datatable(df_tuition_salary %>%
select(name, mean_net_cost, state) %>%
filter(mean_net_cost >= input$input_budget[1],
mean_net_cost <= input$input_budget[2],
state == input$input_state) %>%
select(name, mean_net_cost))
return(shiny_tuition_salary)
})
output$df <- renderDataTable({
dataset()
})
}
Currently nothing is displayed under the Table tab in the app. The app also successfully displays the table when DataTable is not used at all (i.e. removing datatable() from the server and using RenderTable instead of RenderDataTable), so I'm positive there's an issue with my implementation of RenderDataTable()
Thanks!
EDIT: Here's the ui code and a sample df_tuition_salary as well
ui <- fluidPage(
titlePanel("What colleges match your budget and rank?"),
# Sidebar laayout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
sliderInput(inputId = "input_budget",
label = "Budget:",
min = 0,
max = 50000,
value = c(0, 15000)),
selectInput(inputId = "input_state",
label = "State (limited data, may limit options):",
choices = df_tuition_salary$state)
),
# Main panel for displaying outputs ----
mainPanel(
tabsetPanel(
id = 'output_df',
# tabPanel("Plot", plotOutput("plot")),
tabPanel("Table", tableOutput("df"))
)
)
)
)
df_tuition_salary:
df_tuition_salary <- data.frame(name = c("Aaniiih Nakoda College", "Abilene Christian University"),
mean_net_cost = c(7508.2414, 24884.0828),
state = c("N/A", "N/A"))
use dataTableOutput() function.
# Main panel for displaying outputs ----
mainPanel(
tabsetPanel(
id = 'output_df',
# tabPanel("Plot", plotOutput("plot")),
tabPanel("Table", dataTableOutput("df"))
)
I have started practicing shiny package for making dashboard, and i am still an amateur at R, please help me to display the data which will be selected using selectinput in the allocated tab which i have created for display of data.
I shall share my ui code as well as server code. Please assist how to display selected data in the data tab created.
ui.R code
library(shiny)
library(shinydashboard)
shinyUI(fluidPage(
titlePanel(h1("Test for application of all the tutorials completed till now")),
sidebarLayout(
sidebarPanel((h2("Information Panel Enter")),
selectInput("data", "Select the dataset for hist analysis",
choices = c("iris","pressure","USArrests", selected = "pressure")),
numericInput("obs", "Select the number of observations for the dataset", value = 5,min = 5,max = 30,step = 1 ),
sliderInput("bins", "Select the number of bins for histogram", value = 6, min = 6, max = 20, step = 1),
radioButtons("color", "selecct the color of histogram" , choices = c("black","purple","brown"))),
mainPanel((h3("Main Panel of all the information display")),
tabsetPanel(type = c("pills"),
tabPanel("Summary" , h4(textOutput("Mysumhead")) ,verbatimTextOutput("Mysum")),
tabPanel("Structure and Observation" , h4(textOutput("Mystrhead")), verbatimTextOutput("Mystr")),
tabPanel("Plot"),
tabPanel("Data" , verbatimTextOutput("Mydata"))))
)))
server.R code
library(shiny)
library(shinydashboard)
library(datasets)
shinyServer(function(input,output){
output$Mysum <- renderPrint({
summary(get(input$data))
})
output$Mysumhead <- renderText({
paste("Data Selected for checking summary is " , input$data)
})
output$Mystr <- renderPrint({
str(get(input$data))
})
output$Mystrhead <- renderText({
paste("Data selected for observing summary of the data is " , input$data)
})
output$Mydata <- renderTable({
data(input$data)
})
})
you are good in all point except one.
In the UI.R, in Data TAB just change to tableOutput("Mydata") and in Server.R change the code inside rendertable({}) change it to get(input$data).
It will be good to go. You should use tableOutput for displaying Table when you want to use renderTable in server side
I have a relatively heavy programme to run based on manually selected input. I would like to have my app such that users select parameters, pres go and then a database is created that can be used to create multiple tables and graphs based on this dataset. But creating the database can only happen once.
Up to now the database is created before running the app, based on user input. See code below for an example.
countries <- c("BEL", "FRA", "AFG")
el_inf_ex <- 1
df_TEST <-data.frame(iso3= c(rep("BEL", 10),rep("FRA", 10),rep("AFG", 10)),
year= c(seq(2001, 2010), seq(2001, 2010), seq(2001, 2010)),
test= rnorm(30)*el_inf_ex)
#The shiney appp has three parts
ui <- fluidPage(
# App title ----
titlePanel("TEST"),
# Sidebar layout with a input and output definitions ----
sidebarLayout(
# 1 Where you select user input ----
sidebarPanel(
# Input: Selector for choosing dataset ----
selectInput(inputId = "Country",
label = "Choose a country:",
choices = countries),
# Input: Numeric entry for number of obs to view ----
sliderInput(inputId = "Year",
label = "Choose a year:",
value = 2018,
min = 2000,
max = 2010),
# Input: Numeric entry for number of obs to view ----
sliderInput(inputId = "el_inf_ex",
label = "El(inf,exrate):",
value = 0.3,
min = 0,
max = 1)
),
# 2 Where you specify the output ----
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(type = "tabs",
tabPanel("Data Input No shock",
# Output: HTML table with requested number of observations ----
h3("I. One title:"),
tableOutput("CI"),
h3("II. Second title:"),
tableOutput("VUL")
)
)
)
)
)
# Define server logic to summarize and view selected dataset ----
server <- function(input, output) {
# Return the MonArr variable
datasetInput_CI <- reactive({
df_TEST %>% filter(iso3 == input$Country, year == input$Year) %>% summarise(blabla = max(test))
})
# Return the Vulnerability variables ----
datasetInput_Vul <- reactive({
df_TEST %>% filter(iso3 == input$Country, year == input$Year)
})
output$CI <- renderTable(datasetInput_CI())
output$VUL <- renderTable(datasetInput_Vul())
}
shinyApp(ui = ui, server = server)
I would thus like to create the dataframe df_TEST in the code such that el_inf_ex can be selected in the app, but the the lines to create the dataset can only be run once. (In my actual application I will have to source other R files) Afterwards, I want to use the output (the dataframe df_TEST) in graphs and tables.
I found the solution myself. The trick is to use the function observe(). Within this function the dataset can be created.
I changed some parts of the example to make everything respond to the button "Update".
countries <- c("BEL", "FRA", "AFG")
#The shiney appp has three parts
ui <- fluidPage(
# App title ----
titlePanel("TEST"),
# Sidebar layout with a input and output definitions ----
sidebarLayout(
# 1 Where you select user input ----
sidebarPanel(
# Input: Selector for choosing dataset ----
selectInput(inputId = "Country",
label = "Choose a country:",
choices = countries),
# Input: Numeric entry for number of obs to view ----
sliderInput(inputId = "Year",
label = "Choose a year:",
value = 2018,
min = 2000,
max = 2010),
# Input: Numeric entry for number of obs to view ----
sliderInput(inputId = "el_inf_ex",
label = "El(inf,exrate):",
value = 0.3,
min = 0,
max = 10),
actionButton("update", "Update")
),
# 2 Where you specify the output ----
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(type = "tabs",
tabPanel("Data Input No shock",
# Output: HTML table with requested number of observations ----
h3("I. One title:"),
tableOutput("CI"),
h3("II. Second title:"),
tableOutput("VUL")
)
)
)
)
)
# Define server logic to summarize and view selected dataset ----
server <- function(input, output) {
Output <- reactiveValues(datasetInput_CI = NULL)
Output <- reactiveValues(datasetInput_Vul = NULL)
storage <- reactiveValues()
observe({
storage$df_Test <- data.frame(iso3= c(rep("BEL", 10),rep("FRA", 10),rep("AFG", 10)),
year= c(seq(2001, 2010), seq(2001, 2010), seq(2001, 2010)),
test= rnorm(30)*input$el_inf_ex)
})
# Return the MonArr variable
observeEvent(input$update, {
Output$datasetInput_CI <- storage$df_Test %>% filter(iso3 == input$Country, year == input$Year) %>% summarise(blabla = max(test))
})
# Return the Vulnerability variables ----
observeEvent(input$update, {
Output$datasetInput_Vul <- storage$df_Test %>% filter(iso3 == input$Country, year == input$Year)
})
output$CI <- renderTable(Output$datasetInput_CI)
output$VUL <- renderTable(Output$datasetInput_Vul)
}
shinyApp(ui = ui, server = server)