Home  >  Q&A  >  body text

Unable to sort variables in columns of dataframe when rendering reactable

<p>I have a column of variables in my data that are not in the correct order and I need to change their order to render the visualization correctly. </p> <p>I've provided a reproducible example to make it easier to understand: </p> <pre class="brush:php;toolbar:false;">library(reactable) library(dplyr) species <- c("setosa", "versicolor") df <- iris %>% filter(Species %in% species) numbers <- c( 100, 300,400, 50) type <- rep(numbers, times=25) df1 <- df %>% mutate(type = type) df2 <- df1 %>% mutate(species_type= case_when(Species == "setosa" ~ paste0(Species,": ", type), Species == "versicolor" ~ paste0(type,": ", Species), TRUE ~ Species )) columns <- list(colDef(minWidth = 140), colDef(align = "center")) columns <- setNames(columns, names(df2)[2:3]) reactable(df2, columns = columns)</pre> <p>I need to sort the species_types in the rendered table so that the species_type with 50 appears first, I have a precomputed dataframe in a similar order to the example above. However, I tried sorting before rendering but still don't get the correct order in the table. What should I do? I tried sorting, thank you very much! </p>
P粉005105443P粉005105443432 days ago449

reply all(1)I'll reply

  • P粉665427988

    P粉6654279882023-08-15 13:04:29

    One option is to rearrange the data based on the type before passing it to the reactable (not sure why this doesn't work for you).

    Note: I simplified the example data by keeping only the Species columns in iris and four rows per Species.

    library(reactable)
    library(dplyr)
    
    species <- c("setosa", "versicolor")
    df <- iris[c(1:4, 51:54), ] %>
      select(Species) %>
      filter(Species %in% species)
    numbers <- c(100, 300, 400, 50)
    type <- rep(numbers, times = 2)
    df1 <- df %>% mutate(type = type)
    df2 <- df1 %>
      mutate(species_type = case_when(
        Species == "setosa" ~ paste0(Species, ": ", type),
        Species == "versicolor" ~ paste0(type, ": ", Species),
        TRUE ~ Species
      ))
    
    columns <- list(colDef(minWidth = 140), colDef(align = "center"))
    columns <- setNames(columns, names(df2)[2:3])
    
    df2 %>
      arrange(type) %>
      reactable(, columns = columns)

    The second option is to sort by type using the defaultSorted parameter:

    reactable(df2, columns = columns, defaultSorted = "type")

    reply
    0
  • Cancelreply