简体   繁体   中英

shiny R: how to sort and remove duplicates in gvisTable dataframe in reactive setting

I am building a shiny app that displays a dataframe sorted by score. However, the dataframe I created has duplicates and is not ordered by the score column. It is sorted fine the first time I move to the tab where the dataframe is displayed in. It messes up the order when I move to another tab, where I am binding a new row to values$df , then go back to the tab where the dataframe is displayed.

gvisTable

The first part of your problem of the dataframe not getting sorted in order was because you are formatting your score and hence these are getting stored as string (factors, to be specific). So these scores were getting sorted by the level of factors. So to avoid that what you need to do is that whenever you define a dataframe make the parameter stringsAsFactors = FALSE . So in your code wherever yo are defining dataframe, for example new_row<- data.frame(rank, team, score) change it to new_row<- data.frame(rank, team, score, stringsAsFactors = FALSE)

The second problem where you were getting duplicates was because your df2 was defined in a global environment and you where rbinding it without clearing the previous values in df2. To solve that you need to clear all the previous rows in df2. To do this one way would be df2<<-df2[0,] . So I have added that in your code as shown below, which seems to have solved your problem.

 df2<- data.frame()
    output$summa2 <- renderGvis({
      #Clear the previous row in df2
      df2 <<- df2[0,]
      for (team_name in unique(values$df$team)){
        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, stringsAsFactors = FALSE)

        df2 <<- rbind(df2, new_row)
        df2 <<- df2[order(as.numeric(df2$score),decreasing=FALSE),]
        df2$rank <<- 1:nrow(df2)
      }

      return(gvisTable(df2[order(df2$score, decreasing=FALSE),]))
    })

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM