简体   繁体   English

闪亮的R:如何在反应式设置中对gvisTable数据框中的重复项进行排序和删除

[英]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. 第一次移动到显示数据框的选项卡时,它的排序很好。当我移动到另一个选项卡时,它弄乱了顺序,在该选项卡中,我将新行绑定到values $ df ,然后返回到该选项卡显示数据框。

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 . 因此,为了避免这种情况,您需要做的是,每当定义一个数据帧时, stringsAsFactors = FALSE使参数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) 因此,在您的代码中,无论您在哪里定义数据帧,例如new_row<- data.frame(rank, team, score)将其更改为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. 获得重复项的第二个问题是因为df2是在全局环境中定义的,并且在不清除df2中先前值的情况下对其进行绑定。 To solve that you need to clear all the previous rows in df2. 要解决此问题,您需要清除df2中的所有先前行。 To do this one way would be df2<<-df2[0,] . 为此,可以使用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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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