Oleole
Oleole

Reputation: 411

R Shiny: how to use a dataframe variable from server.R in ui.R

I am trying to use the values$df dataframe variable from server.R in ui.R to display all the field names of the dataframe as checkbox in the side panel. But I get an error saying Error: object 'values' not found.

Here is what I have in the server.R file:

  values<- reactiveValues() 
  values$df<- data.frame() # creates an empty dataframe

  # actionButton 
  mdf<- eventReactive(input$click_counter, {
    name<- input$name
    gender<- input$gender
    college<- input$college
    team<- input$team
    score<- input$score

    new_row<- data.frame(name,college,gender,team,score)

    return(new_row)
  })

  observeEvent(input$click_counter, {
    name<- input$name
    gender<- input$gender
    college<- input$college
    team<- input$team
    score<- as.numeric(input$score) # convert to numeric here to make sorting possible
    rank<- 0


    new_row<- data.frame(rank,name,college,gender,team,score)


    values$df<- rbind(values$df, new_row)
    values$df<- values$df[order(-values$df$score),]
    values$df$rank<- 1:nrow(values$df)
  })

  output$nText<- renderDataTable({
    mdf()
  })

  output$nText2<- renderDataTable({
    values$df
  }, options = list(orderClasses = TRUE,lengthMenu = c(5, 10, 30), pageLength = 5))

And this is what I have in the ui.R file:

sidebarLayout(
  sidebarPanel(
    checkboxGroupInput('nText2',
                       'Columns in players to show:',
                       names(values$df),
                       selected = names(values$df))
  ),

Upvotes: 2

Views: 2203

Answers (2)

Ryan Morton
Ryan Morton

Reputation: 2695

Getting the server to render the UI allows you to continue working with the data frame as you are for other server side operations. Without having the data frame reproducible, I can't say for certain whether THIS data frame will work, but I hope this gives you a good push forward.

server.R:

output$nText2ui <- renderUI({checkboxGroupInput('nText2',
                          'Columns in players to show:',
                          names(values$df),
                          selected = names(values$df))
                         })

ui.R:

sidebarLayout(
  sidebarPanel(
   htmlOutput("nText2ui")
    )
  )

Upvotes: 1

nteetor
nteetor

Reputation: 1234

I am not quite sure when you assign the values object. However, if you are not already using a global.R file I suggest using one. In it you can assign values and the object will be available in both server.R and ui.R. Place global.R in the same folder as the two other files.

Upvotes: 1

Related Questions