using assign inside reactiveValues for Shiny?

Viewed 198

I am wondering, why assign function is not working inside the reactiveValues? I need to apply a function that will define reactiveValues (zeros) to all elements in a vector. Those elements are not known in advance, because they are column names of all variables from initially opened csv file. So I cannot simply set values one by one. Any suggestion is highly appreciated.

ui <- shinyUI(fluidPage(

  titlePanel("Wondering"),

  sidebarLayout(

    sidebarPanel(
        actionButton(inputId = "add_one", label = "", icon = icon("plus"))
      ),

    mainPanel(
      tabsetPanel(
        tabPanel("Simple example",textOutput("test1"))
      )
    )
  )
)
)

##########
# SERVER #
##########

server <- shinyServer(function(input, output) {

  col_names <- c("A", "B")

  # Assign zeros to all elements from col_names
  # Please, use the assign function to do that!
  rv <- reactiveValues(

    # 1 How can I assign the initial value of zero to all column names? 

    # This is easy:
    A = 0, B = 0

    # But, in reality, in my app I do not know the variable names in advance, I just extract them and save
    # in the col_names vector. Now, I need to assign initial value of zero to all column names

    # I thought this might work, but no luck: All arguments passed to reactiveValues() must be named.
    #for (k in 1:length(col_names)){
    #
    #  assign(col_names[k], 0)  
    #}

    )

  # Sure, I will later have to figure out how to define observeEvent(s) for the unknown number of column names, but I am not there yet...
  observeEvent(input$add_one, {
    rv$A <- rv$A + 1
  })

  observeEvent(input$add_one, {
    rv$B <- rv$B + 1
  })

  # Output text
  output$test1 <-renderText({

    paste(rv$A, rv$B)

  })

})

shinyApp(ui = ui, server = server)
1 Answers

You could do:

rv <- reactiveValues()
for(colname in col_names){
  rv[[colname]] <- 0
}
Related