Read in multiple values in R shiny textInput - r

Is it possible to read in multiple values in textInput in R shiny? Look at a simple example below. I want to be able to produce a sum (or another R function) on the user entering valueS. Can a user enter: 1, 2, 3, 4 and the see the sum of these numbers below?
shinyUI(fluidPage(
# Copy the line below to make a text input box
textInput("text", label = h3("Text input"), value = "Enter text..."),
hr(),
fluidRow(column(3, verbatimTextOutput("value")))
))
shinyServer(function(input, output) {
# You can access the value of the widget with input$text, e.g.
output$value <- renderPrint({ input$text })
})

Related

How can I properly link my ui and server files for this Shiny app

I am trying to put together a Shiny app; this is far outside what I would normally be doing. Originally, I put together a function (coolFunction below) that takes three inputs:
x - A string
y - A string taken from a list
t - A number
and returns either a data frame or a list. The UI file seems to put everything together correctly:
# Required package for shiny apps
library(shiny)
# Possible responses for part of speech
ppos = c("one", "two", "three")
ui <- fluidPage(
# Title using HTML
h1("Cool Title Here", align = "center"),
# Put results in sidebar
sidebarPanel(
h3("Results"),
p("Descriptive words"),
renderTable("finresult")
),
# Main panel for instructions and input
mainPanel(
# Sidebar for input
h3("Instructions", align = "center"),
p("Words here. Once you've entered all of the required information, click the \"go\" button to get your results."),
# Numbered list of instructions for input
tags$ol(
# Item 1
tags$li("Instructions for Point 1."),
# Input 1
textAreaInput("x", "Enter your string here:", rows = 3),
# Item 2
tags$li("Instructions for Point 2."),
# Input 2
sliderInput("t", "Indicate your desired number of results:", value = 10,
min = 1, max = 50),
# Item 3
tags$li("Instructions for Point 3."),
# Input 3
selectInput("y", "Pick from list:", ppos)
# Close numbered list
)
# Close sidebar
),
# Action button to go
actionButton("button", label = "Do it!")
# Close fluidpage
)
but the server file doesn't seem to produce anything. Ideally, I'd like the user to hit the "go" button to make the script run and generate output each time.
shinyServer(
function(input, output, session) {
observeEvent(input$button,
coolFunction(input$x, input$y, input$t),
output$finresult <- renderTable(finresult)
)
})
I'm sure I've missed something fundamental. Does anyone see it?
I discovered the answer. It is here:
shinyServer(
function(input, output, session) {
observeEvent(input$button,
output$finresult <- renderTable({
coolFunction(input$x, input$y, input$t)})
)
})

how to use conditionalpanel() in shiny r

I am trying to create a shiny app where it allows you to select an input of what operation calculate. if the user chooses "Addition" it will show the two numeric input boxes (so they can input two numbers), if the user chooses "square" it will show only one numeric input box to square.
With this, I use conditionalPanel and if the condition is satisfied, it fetches through uiOutput() the numericInputs that I want. and same thing for square.
Now when I run this app, the conditional panels do not appear. Where did I go wrong? Thanks for checking out my question.
ui <- fluidPage( theme = shinytheme("slate"),
titlePanel("Basic Calculator"),
sidebarPanel(
selectInput("ops","Select what Operation use",choices = c("ADDITION","SQUARE")),
helpText("Please input the appropriate number depending on the operations"),
conditionalPanel("input.ops=='ADDITION'", uiOutput("var2")),
conditionalPanel("input.ops=='SQUARE'", uiOutput("var1"))
),#sidebar panel
)#fluidpage
server <- function(input, output) {
output$basicmath <- renderText( ifelse(input$ops=="ADDITION",input$a+input$b,
ifelse(input$ops=="SUBTRACTION",input$a-input$b,
ifelse(input$ops=="SQUARE",input$a*input$a,
ifelse(input$ops=="SQUARE ROOT",sqrt(input$a),
ifelse(input$ops=="MULTIPLICATION",input$a*input$b,"not a valid operation"))))),
output$var2 <- renderUI({
helpText("this will show to input two numerics to be added")
}) ,
output$var1 <- renderUI({
helpText("this will show to input one numeric to square")
})
)}
shinyApp(ui = ui, server = server)
The key issue you were having is that you put the uiOutputs inside the calculation output that you anticipated. It is better to separate them, since the calculation output won't run until it has the necessary prerequisite values (your input values). In addition, because you hadn't specified an output location for basicmath, the app didn't know where to put anything inside that call to renderText(). Below is working code that gets the right UI elements to appear.
One other thing you were missing in your renderUI was the use of tagList(). This helps ensure that all of your elements are packaged together, not just the last one.
Note that the math part does not work, but it looks like that was just a placeholder. When you do start to use it, be sure to use unique ids for each input. You have several instances of input$a and input$b, which probably isn't a workable approach.
library(shiny)
library(shinythemes)
ui <- fluidPage( theme = shinytheme("slate"),
titlePanel("Basic Calculator"),
sidebarPanel(
selectInput("ops","Select what Operation use",choices = c("ADDITION","SQUARE")),
helpText("Please input the appropriate number depending on the operations"),
conditionalPanel("input.ops=='ADDITION'", uiOutput("var2")),
conditionalPanel("input.ops=='SQUARE'", uiOutput("var1"))
),
mainPanel(
textOutput("basicmath")
)
)#fluidpage
server <- function(input, output) {
output$var2 <- renderUI({
tagList(
helpText("this will show to input two numerics to be added"),
splitLayout(
numericInput("var2a", label = "Input one number", value = NULL),
numericInput("var2b", label = "Input another number", value = NULL)
)
)
})
output$var1 <- renderUI({
tagList(
helpText("this will show to input one numeric to square"),
numericInput("var1a", label = "Input a number", value = NULL)
)
})
output$basicmath <- renderText( {ifelse(input$ops=="ADDITION",input$a+input$b,
ifelse(input$ops=="SUBTRACTION",input$a-input$b,
ifelse(input$ops=="SQUARE",input$a*input$a,
ifelse(input$ops=="SQUARE ROOT",sqrt(input$a),
ifelse(input$ops=="MULTIPLICATION",input$a*input$b,"not a valid operation")))))
})
}
shinyApp(ui = ui, server = server)

R get value from selectInput updated

I have a selectInpunt updated, and with this last value, I want to get information from a dataframe, but I can't get the value of the last selectInput, I have just the result "character(0)". The dataframe open but I can't get the value corresponding to input...The values of the first selectInput are the names of different data.frames. I can get the data.frame, but I can not extract the information corresponding to the input of the second selectInput.
library(shiny)
liste<-c("BCE","FED")
ui<-tagList(
navbarPage(
"Evolutions Economiques",
tabPanel("Observation",
# Application title
titlePanel("Evolutions Economiques"),
# Sidebar with a slider input for number of bins
#sidebarLayout(
sidebarPanel(
h1("Selection des donnees"),
selectInput("Source","Source :",
choices =liste),
selectInput("indic","Indicateur :",
choices = NULL)
),
# Show a plot of the generated distribution
mainPanel(
tabsetPanel(type="tabs",
tabPanel("Description",verbatimTextOutput("summary"),
)
))
)
))
library(shiny)
library(dplyr)
BCE<-data.frame(Indice=c("A","B"),Description=c("Alors","Pouipoui"))
FED<-data.frame(Indice=c("C","D"),Description=c("So","Birdyy"))
# Define server logic required to draw a histogram
shinyServer(function(input, output,session) {
observeEvent(input$Source,{
data<-get(input$Source)
updateSelectInput(session,"indic",
choices = data$Indice)
})
output$summary<-renderPrint({
data<-get(input$Source)
data<-filter(data,Indice==input$indic)
data<-data$Description
data
})
})

How to validate user input in shiny

I'm working on a very simple Shiny app that takes in a DNA codon and returns the corresponding amino acid. My issue is that I want to validate the user input so that it can only accept 3 letter (a single codon), must be capital letters, and only accept the DNA bases ( A, C, T, or G). I've had a look at Shiny's validation article, but keep on running into errors.
Here is the code I have so far:
ui.R
library(shiny)
library(shinythemes)
shinyUI(fluidPage(
theme = shinytheme("slate"),
# Application title
titlePanel("Codon lookup"),
#
sidebarLayout(
sidebarPanel(
textInput(
inputId = "codon",
label = "Enter a codon",
value = ""),
actionButton(inputId = "go", label = "Search")
),
#
mainPanel(
verbatimTextOutput("aminoacid")
)
)
))
server.R
library(shiny)
library(Biostrings)
shinyServer(function(input, output) {
data <- eventReactive(input$go, {
#validate somehow
input$codon
})
output$aminoacid <- renderText({
GENETIC_CODE[[as.character(data())]]
})
})
Also, if anyone know of an easy way to retrieve the amino acid's full name, rather than just the single letter notation, that would be helpful. Any other suggestions are welcomed.
That reactive is not really the right place to do the validation in this case since you are not using GENETIC_CODE there. So I moved it into the renderText output node. If you had a reactive doing the lookup you could do it there.
I looked at GENETIC_CODE, and it seems to make more sense to do this as a dropdown anyway and use that as validation. So I went ahead and put a selectInput in there using renderUI, as you have more flexibility if you create the input control in the server usually.
I also moved the Search button to above the codon select control as it was getting covered up by the selection.
library(shiny)
library(shinythemes)
u <- shinyUI(fluidPage(
theme = shinytheme("slate"),
# Application title
titlePanel("Codon lookup"),
#
sidebarLayout(
sidebarPanel(
actionButton(inputId = "go", label = "Search"),
uiOutput("codonselection")
),
#
mainPanel(
verbatimTextOutput("aminoacid")
)
)
))
library(Biostrings)
s <- shinyServer(function(input, output) {
data <- eventReactive(input$go, {
input$codon
})
output$codonselection <- renderUI({
choices <- names(GENETIC_CODE)
default <- "TTC"
selectInput("codon",label="Select Codon",choices=choices,selected=default)
})
output$aminoacid <- renderText({
lookupcodon <-as.character(data())
if (lookupcodon %in% names(GENETIC_CODE)){
return(GENETIC_CODE[[ lookupcodon ]])
} else {
return("Name not in GENETIC_CODE")
}
})
})
shinyApp(u,s)
Screen shot of it working:

Producing dynamic/multiple input boxes to collect data depending on user selection in Shiny R

I am trying to build an app in Shiny that (1) asks user for number of Assets in his/her portfolio. Depending on the numeric entry, (2) the user is presented with one numeric box to enter the % of portfolio owned AND the Ticker/name of the Asset.
For instance, If the user enters 3 for number of assets in portfolio, he will be presented with something like this:
Asset1 ----> Enter ticker______ Enter Wight______
Asset2 ----> Enter ticker______ Enter Wight______
Asset3 ----> Enter ticker______ Enter Wight______
This is suppose to be dynamic so the greater the number of assets, the greater the input fields.
Finally, in step (3), I want to save the entered information for each Asset in a table and display the table.
Here is what I have got and it is no where near what I need it to be. I am totally new to Shiny and that is half the reason for my troubles:
UI.R
shinyUI(pageWithSidebar (
headerPanel( "Portfolio Returns"),
sidebarPanel(
numericInput("assets", label = "Enter Total Assets", value="")
),
mainPanel(
tableOutput("table"))
)
)
server.R
shinyServer(
function(input,output) {
output$DynamicAssets <- renderUI ({
Assets <- as.integer(input$assets)
for(i in 1:Assets,function(i) {
"ticker" = textInput("Ticker", label="Enter Ticker", value="Enter Ticker"),
"weight" = numericInput ("AssetWeight", label="weights of Assets", value="")
})
})
})
})
I know the code is in complete because i have no idea what to do next. this is all that i figured out from seraching the net. Your help would be greatly appreciated.
ui.R
library(shiny)
shinyUI(pageWithSidebar (
headerPanel( "Portfolio Returns"),
sidebarPanel(
numericInput("assets", label = "Enter Number of Assets in Portfolio", value="1"),
uiOutput("tickers")
),
mainPanel()
))
server.R
-Note that to pass multiple items in the renderUI() function you have to group them into a list, and here lapply() is creating a list of lists.
library(shiny)
shinyServer( function(input, output, session) {
output$tickers <- renderUI({
numAssets <- as.integer(input$assets)
lapply(1:numAssets, function(i) {
list(tags$p(tags$u(h4(paste0("Asset ", i)))),
textInput(paste0("ticker", i), label = "Ticker Name", value = "Enter ticker..."),
numericInput(paste0("weight", i), label = "Weight of Asset", value=0))
})
})
})

Resources