From a34da09b7f79ce166fb36c9c69c9a266467ceadf Mon Sep 17 00:00:00 2001 From: yilong zhang Date: Sat, 2 Dec 2023 20:41:57 +0000 Subject: [PATCH] add `reactable_to_df` function to convert output to a data frame --- R/reactable2.R | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/R/reactable2.R b/R/reactable2.R index 4ffc0d6..52ce7b9 100644 --- a/R/reactable2.R +++ b/R/reactable2.R @@ -60,3 +60,34 @@ reactable2 <- function(data, tbl } } + +#' Convert reactable to a data frame +#' +#' @param x A `reactable` HTML widget +#' +#' @return A data frame +#' +reactable_to_df <- function(x){ + + # table data + tbl1 <- do.call(cbind, jsonlite::fromJSON(x$x$tag$attribs$data)) + + # table columns + columns <- x$x$tag$attribs$columns + tbl2 <- list() + for(i in seq_along(columns)){ + if(! columns[[i]]$id %in% ".details"){ + if(is.null(columns[[i]]$show)){ + tbl2[[i]] <- unlist(columns[[i]]) + } + } + } + tbl2 <- dplyr::bind_rows(tbl2) + + # output + tbl <- data.frame(tbl1[, tbl2$id]) + + attr(tbl, "column_header") <- paste(tbl2$name, collapse = "|") + + tbl +}