我正在尝试在可反应中创建 colGroups,但要更改我要分组的列的值。因此,在我的示例数据集中,列的值group
是red
并且blue
可以通过用户交互进行更改,因为我想将可反应嵌入到闪亮的应用程序中。
第一个代码示例提供了一个带有静态编码的列名的示例,并且可以正常工作。
但是我正在寻找一种方法来重新创建第一个代码示例的结果,而不是显式地对 colnames 进行编码,我在第二个代码示例中进行了尝试。
但我不明白为什么它给了我错误Error in reactable(., columns = map(.x = seq_along(data_wider_colnames), : `columns` must be a named list of column definitions
。列定义中一定有问题;columnGroups-definition 似乎有效。
library(reactable)
library(tidyr)
data = tibble(group = c("red","blue"),
month = rep("august", 2),
valueOne = c(500,1000),
valueTwo = c(200, 2000),
valueThree = c(100, 5000))
### bring data into wider format and seperate new colnames with `.`
data_wider = data %>%
pivot_wider(names_from = group, names_glue = "{group}.{.value}", values_from = c("valueOne", "valueTwo", "valueThree"))
### pipe wider data into reactable
data_wider %>%
reactable(
### rename all new colnames
columns = list(
"red.valueOne" = colDef(name = "valueOne"),
"blue.valueOne" = colDef(name = "valueOne"),
"red.valueTwo" = colDef(name = "valueTwo"),
"blue.valueTwo" = colDef(name = "valueTwo"),
"red.valueThree" = colDef(name = "valueThree"),
"blue.valueThree" = colDef(name = "valueThree")),
### create columngroups
columnGroups = list(
colGroup(name = "red", columns = c("red.valueOne", "red.valueTwo", "red.valueThree")),
colGroup(name = "blue", columns = c("blue.valueOne", "blue.valueTwo", "blue.valueThree")))
)
library(reactable)
library(tidyr)
library(purr)
library(stringr)
data = tibble(group = c("red","blue"),
month = rep("august", 2),
valueOne = c(500,1000),
valueTwo = c(200, 2000),
valueThree = c(100, 5000))
### bring data into wider format and seperate new colnames with `.`
data_wider = data %>%
pivot_wider(names_from = group, names_glue = "{group}.{.value}", values_from = c("valueOne", "valueTwo", "valueThree"))
### asign new colnames into a help vector to extract/and change names attribute from it in colDef()
data_wider_colnames = colnames(data_wider[,2:ncol(data_wider)])
### asign distinct values for column `group` into new vector
distinct_group_values = data$group
### asign new colnames for each distinct value of `group` into a help vector to declare colGroups() and corresponding colums
distinct_group_colnames = map(seq_along(names), .f = ~ str_subset(data_wider_colnames, distinct_group_values[.x]))
data_wider %>%
reactable(
columns = map(.x = seq_along(data_wider_colnames),
.f = ~ set_names(list(colDef(name = str_extract(data_wider_colnames[.x], "(?<=\\.).*"))), data_wider_colnames[.x])),
columnGroups = map(.x = seq_along(distinct_group_values),
.f = ~ colGroup(name = distinct_group_values[.x], columns = distinct_group_colnames[.x][[1]]))
)