Unable to sort variables in columns of dataframe when rendering reactable
P粉005105443
P粉005105443 2023-08-14 14:23:14
0
1
436
<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粉005105443
P粉005105443

reply all(1)
P粉665427988

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")
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!