0

I'm wanting to show an HoT table per slicing factor in shiny, from a dataset that has dynamic slices. Below is my best attempt to achieve this, but the output is a duplicated table. You can see how everything looks correct from the split data frames in the print out, but it appears RHandsontable has an issue where it's only pointing to the last HoT created in the map.

Any idea how to achieve showing the distinct dataframes?

library(shiny)
library(dplyr)
library(rhandsontable)
library(purrr)
ui <- fluidPage(

  uiOutput('tables')
)

server <- function(input, output) {
  mtcars$slc <- sample(c('aaa','bbb'),nrow(mtcars),replace=TRUE)
  df <- mtcars
  
  getSlice <- function(df_tmp,slca){
    print(slca)
    df_tmp <- df_tmp %>% filter(slc==slca)
    df_tmp
  }
  
  output$tables <- renderUI({
    slices <- unique(df$slc)
    input_dfs <- map(slices,~getSlice(df,.x))
    
    for(i in 1:length(slices)){
      print(input_dfs[[i]]) # proof that there are two distinct data 
                            #  frames going into renderRHandsontable()
      output[[slices[i]]] <- renderRHandsontable(rhandsontable(input_dfs[[i]]))
    }
    
    out <- map(slices,function(x){
      rHandsontableOutput(x)
    })
    print(out) # div ids are correctly distinct, but the tables that show are not!
    out
  })
}

shinyApp(ui = ui, server = server)

Output - all 'aaa' duplicates...

enter image description here

1 Answer 1

1

Use local() in your for loop.

for(i in 1:length(slices)){
  local({
    i <- i
    print(input_dfs[[i]]) # proof that there are two distinct data 
    #  frames going into renderRHandsontable()
    output[[slices[i]]] <- renderRHandsontable(rhandsontable(input_dfs[[i]]))
  })
}
2
  • That works great! Thank you. Can you share some of the intuition for why this works?
    – burchz
    May 26 at 12:54
  • In shiny, for loops do not work as you might think. This is mainly due to lazy evaluation.
    – YBS
    May 26 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.