I am completely new to Shiny, and I am trying to prepare a R Markdown file where I need to get a text input from the user to use it in the program.
The UI and Server lines are in the same R Markdown as follows:
textInput('year1', h4('Start_year:'), value = 'Enter year...')
date1 <- reactive(input[['year1']])
date1
When I run this code I can enter a year which is replicated in the output box. I included the “date1” line just to see the text entered. The problem is that I need to assign the year entered by the user to a variable I use in the R program.
When I try to convert that variable to double using the following code I get the message:
Error: cannot coerce type ‘closure’ to vector of type ‘double’
textInput('year1', h4('Start_year:'), value = 'Enter year...')
date1 <- reactive(input[['year1']])
date10 <- as.double(date1)
How can I make it work? Is there a better alternative to get a simple year input in a R Markdown document? I will appreciate any guidance. Thanks a lot.
There are a few different ways to combine RMarkdown with Shiny explained here, but from your question I understand that you want to create an interactive RMarkdown which uses Shiny, i.e. the beginning of your document specifies something like
---
title: "title"
output: html_document
runtime: shiny
---
Here are three different options how you can use your textInput
for your output. None is strictly "better" than the others for all use cases. The example converts your text input to numeric and uses it for point size and title of a simple plot.
Usually the easiest way for simple tasks - you can access your input
in any reactive context, so no need to create additional reactive objects:
inputPanel(
textInput('year1', h4('Start_year:'), value = 'Enter year...')
)
renderPlot({
ps <- max(as.double(input$year1), 1, na.rm = TRUE)
ggplot(iris, aes(x = Petal.Width, y = Petal.Length, color = Species)) +
geom_point(size = ps) +
labs(title = paste0("points size: ", ps ))
})
Create a reactive
for this particular input - this is the approach shown in the question and will work if you use date1()
instead of date1
(as suggested in a previous comment):
ps <- reactive(
max(as.double(input$year1), 1, na.rm = TRUE)
)
renderPlot({
ggplot(iris, aes(x = Petal.Width, y = Petal.Length, color = Species)) +
geom_point(size = ps()) +
labs(title = paste0("points size: ", ps() ))
})
Create a general reactiveValues
list for your document/application. This can be used similarly to the input
object. I find this rather useful for storage of processed data, models, etc.. that need to be accessed in different parts of the document/application.
values <- reactiveValues()
# assign in one reactive environment
observe({
values[["ps"]] <- max(as.double(input$year1), 1, na.rm = TRUE)
})
# use in another reactive environment
renderPlot({
ggplot(iris, aes(x = Petal.Width, y = Petal.Length, color = Species)) +
geom_point(size = values[["ps"]]) +
labs(title = paste0("points size: ", values[["ps"]] ))
})