Unable to sort variables in columns of dataframe when rendering reactable
P粉005105443
2023-08-14 14:23:14
<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>
One option is to rearrange the data based on the
type
before passing it to thereactable
(not sure why this doesn't work for you).Note: I simplified the example data by keeping only the
Species
columns iniris
and four rows perSpecies
.The second option is to sort by
type
using thedefaultSorted
parameter: