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.
-
Can you provide a reproducible example? There seems to be some problem with the code you provided. – SBista Mar 10 '17 at 11:57
-
@SBista I have edited my question and pasted what I have in my app.R file. Thanks so much for your help in advance :) – Oleole Mar 11 '17 at 08:23
-
@SBista fyi the fourth tab "참가신청서" is where I am taking user information and the second tab "분석" is where gvisTable is displayed. – Oleole Mar 11 '17 at 08:36
-
@SBista Also, I would greatly appreciate it if you have any ideas on how to make the "참가신청서" tab to be a loginable page! – Oleole Mar 11 '17 at 08:37
-
You want just a tab to be a loginable page or you want the entire app to be loginable? – SBista Mar 11 '17 at 13:15
-
@SBista I just want the tab to be a loginable page – Oleole Mar 12 '17 at 11:35
-
One way to do it would be to put the whole tab item in `renderUI`, something in the lines of [this](http://stackoverflow.com/a/28997605/5894457). The second option could be using conditional panels. – SBista Mar 12 '17 at 11:36
1 Answers
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!

- 7,479
- 1
- 27
- 58