Reputation: 3
I am trying to create a function to simplify a long reactive expression. The goal is to create a data frame out of user-inputs. The goal of the function is to dynamically refer to different inputs in the UI based on the function argument. The function has a "day" argument which should be pasted with input$A
to create input$A<day>
where <day>
is an input to my server-side function. In the below example, I would run foo(day = 1)
in my main server function, which would create a dataframe out of the inputs the user entered into "Day 1" of my app.
I very naively started with:
foo <- function(day) {
df <- data.frame(
"A" = paste0("input$A", day),
"B" = paste0("input$B", day)
)
}
I understand this won't work and just creates a dataframe with rows of text saying "input$Aday" and "input$Bday". I have since explored using eval(parse())
, rlang
, etc and have not gotten this to work. Any help would be greatly appreciated.
Upvotes: 0
Views: 1085
Reputation: 7106
Here are two ways to refer to the input as an object:
library(tidyverse)
library(shiny)
ui <- fluidPage(
textInput('A1', 'InputA1', value = 'hello'),
textInput('B1', 'InputB1', value = 'How are you?')
)
server <- function(input, output, session) {
foo1 <- function(day) {
df <- data.frame(
"A" = input[[str_c('A', day)]],
"B" = input[[str_c("B", day)]]
)
}
foo2 <- function(day) {
df <- tibble(
"A" = parse(text =str_c('input$A', day)) %>% eval(),
"B" = parse(text =str_c('input$B', day)) %>% eval()
)
}
observe({
print(foo1(day = 1))
print(foo2(day = 1))})
}
shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:6240
#> A B
#> 1 hello How are you?
#> # A tibble: 1 x 2
#> A B
#> <chr> <chr>
#> 1 hello How are you?
Created on 2021-06-26 by the reprex package (v2.0.0)
Upvotes: 1