bjorn2bewild
bjorn2bewild

Reputation: 1019

Referencing variables with the same prefix in R

I'm looking for a way to reference variables with the same prefix in R. Specifically, I'm looking to define the output variables in the server section of this R Shiny app in one line. In the full version of the app, I have many rows of slider inputs, so manually entering each line is too cumbersome. I've solved this problem for the ui section by using paste0 to create the input/output variables.

library(shiny)

v1 <- lapply(1:2, function(i){
  fluidRow(column(1,sliderInput(inputId = paste0("B",i),
           label = NULL,value = 0,min=0,max = 100, step=5)))
})

v2 <- lapply(1:2,function(i){
  fluidRow(column(1, textOutput(paste0("A",i))))
})

v3 <- c(rbind(v1,v2))

ui <- fluidPage(fluidRow(v3))

server <- function(input, output) {
  output$A1 <- renderText({input$B1})
  output$A2 <- renderText({input$B2})
}

shinyApp(ui = ui, server=server)

I tried to implement the recommendation from this post. Namely:

z <- sapply(1:2, function(x) assign(paste0("A",x), renderText({input$B[x]}), pos=1))

server <- function(input, output) {
      z
    }

However, this did not work. Is there a way to more eloquently define the output variables from the server section in one line in this Shiny context?

Upvotes: 1

Views: 390

Answers (1)

Jim Chen
Jim Chen

Reputation: 3749

The easiest way is use double bracket [[]] to call your widget.

The following code should work perfectly.

library(shiny)
number_of_ui <- 5

v1 <- lapply(1:number_of_ui, function(i){
  fluidRow(column(1,sliderInput(inputId = paste0("B",i),
                                label = NULL,value = 0,min=0,max = 100, step=5)))
})

v2 <- lapply(1:number_of_ui,function(i){
  fluidRow(column(1, textOutput(paste0("A",i))))
})

v3 <- c(rbind(v1,v2))

ui <- fluidPage(fluidRow(v3))

server <- function(input, output) {

  create_server<-function(i){
    output[[paste0("A",i)]]<-renderText({
      input[[paste0("B",i)]]
    })
  }

  lapply(1:number_of_ui, create_server)
}

shinyApp(ui = ui, server=server)

Upvotes: 1

Related Questions