rhandsontable
rhandsontable copied to clipboard
Get selected rows after ordering by a column
Selected rows can be accessed in input$hot_select$select$r and input$hot_select$select$r2 for the first and last selected rows by the user respectively. This works perfect if users don't change the rows order. However, if we sort the table by a column, the index returned by (---)$r and (...)$r2 are referred to the original table and not to the ordered one. This is not a problem if I only select one row or I dont'r order the table, but if I select multiple rows and the table is sorted, I am not capable to obtain the actual index values. For instance, if the original order is 1, 2, 3, 4, the sorting result is 1, 3, 2, 4 and I select the first 3 rows, I will only get (...)$r = 1 and (...)$r2 = 2, losing information about 3.
Here's a code to better illustrate what I mean. My goal is to select the first 3 rows and print them in another table. That is achieved if table is not sorted, by it fails if we sort by the second column:
library(rhandsontable)
library(shiny)
DF <- data.frame(X1 = c("A", "B", "C", "D"), X2 = c(1, 4, 3, 2))
runApp(shinyApp(
ui = fluidPage(
rHandsontableOutput("hot"),
br(),
tableOutput("trimmed")
),
server = function(input, output, session) {
output$hot <- renderRHandsontable({
rhandsontable(DF, selectCallback = TRUE) %>% hot_cols(columnSorting = TRUE)
})
output$trimmed <- renderTable({
selectedRows = (input$hot_select$select$r:input$hot_select$select$r2)
print(DF[selectedRows,])
})
})
)
Is there a way to achieve this? If, instead of getting only the first and the last selected rows, we could get a vector with all the selected rows, I think this wouldn't be a problem any more.
Thanks in advance.
Thanks for changes that return the correct selected row indices after ordering by row or column. Works great.
Is there a way to return the (new) reordered rows using hot_to_r. It seems to always return the old (previous) order of the rows. The new code uses a nifty call toPhysicalRow
r_all.push( this.toPhysicalRow(i) + 1 );
Can something similar be done with hot_to_r so that the modified table with reordered rows can be returned?
Just a small note: currently the row number returned by select$r
is still incorrect after sorting (i.e. unchanged), whereas select$rAll
is OK. Bug or feature?
Cheers, Rick
@rickhelmus thanks for posting that - this solved everything for me :)