Oleole
Oleole

Reputation: 411

shiny R: how to use for loop in shiny app

I am trying to take the dataframe values$df and create another dataframe df by using for loop. In the for loop, I would like to display the average score of each team. Although it generates reactive outputs for unique(values$df$team) in output$summa2, it does not generate any outputs for what's inside the for loop. And when I add return(df) at the end, it only generates the first row of the dataframe, not all.

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

  values<- reactiveValues() 
  values$df<- data.frame()

  observeEvent(input$click_counter, {
    name<- input$name
    gender<- input$gender
    college<- input$college
    team<- input$team
    score<- as.numeric(input$score)
    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,decreasing=TRUE),]
    values$df$rank<- 1:nrow(values$df)
  })

output$summa2 <- renderPrint({
    unique(values$df$team) # this works
    for (team_name in unique(values$df$team)){ #this does NOT work
      rank<- 0
      team<- team_name
      score<- format(mean(values$df[values$df$team==team_name,]$score), digits=4)

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

      df<- rbind(df, new_row)
      df<- df[order(df$score,decreasing=TRUE),]
      df$rank<- 1:nrow(df)
      #return(df)
    }
  })

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

verbatimTextOutput("summa2")

Upvotes: 2

Views: 5438

Answers (1)

B&#225;rbara Borges
B&#225;rbara Borges

Reputation: 919

I'd change the renderPrint to this:

output$summa2 <- renderPrint({
  df <- data.frame()
  for (team_name in unique(values$df$team)){ #this does NOT work
    local({
      rank <- 0
      team <- team_name
      score <- format(mean(values$df[values$df$team==team_name,]$score), digits=4)

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

      df <<- rbind(df, new_row)
      df <<- df[order(df$score,decreasing=TRUE),]
      df$rank <<- 1:nrow(df)
    })
  }
  return(df)
})

Upvotes: 1

Related Questions