我不知道如何将rpivottable的输出保存在shine中。下面是我的最低工作示例供参考。
library(tidyverse)
library(shiny)
library(shinydashboard)
ui <-
dashboardPage(
skin = "green",
dashboardHeader(
title = "Test",
titleWidth = 280
),
dashboardSidebar(
width = 280,
sidebarMenu(
menuItem(text = "Output", tabName = "Out1", icon = icon("file-upload"))
)
),
dashboardBody(
tabItems(
tabItem(
tabName = "Out1",
fluidRow(column(width = 10, strong("Data")), align = "center"),
br(),
fluidRow(rpivotTableOutput("Data1"))
)
)
)
)
server <-
function(input, output){
library(rpivotTable)
output$Data1 <-
renderRpivotTable(
rpivotTable(
data = mtcars
, rows = "cyl"
, cols = "gear"
, height = "780px"
)
)
}
runApp(
list(ui = ui, server = server)
, launch.browser = TRUE
)
编辑/更新:在rvest
和xlsx
包的帮助下,我们可以将提取的html数据透视表保存为xls文件。更新代码如下
我同意@danlooo的评论,即尝试从rpivotTable
的渲染中提取数据可能不是最好的方法。然而,我可以提供一种提取生成的透视表的HTML代码的方法。
下面的代码提取生成的透视表的html代码,使用rvest从该html中提取一个dataframe
,最后使用xlsx
进行导出。更多关于shine和js之间交互的信息可以在本文中找到
该代码生成一个包含rpivotTable 生成的数据透视表的xls文件
library(tidyverse)
library(shiny)
library(shinydashboard)
library(rpivotTable)
library(shinyjs)
library(dplyr)
library(rvest)
library(xlsx)
ui <-
dashboardPage(
skin = "green",
dashboardHeader(
title = "Test",
titleWidth = 280
),
dashboardSidebar(
width = 280,
sidebarMenu(
menuItem(text = "Output", tabName = "Out1")
),
hr(),
useShinyjs(),
actionButton(inputId = "btnExport", "Export Table")
),
dashboardBody(
tabItems(
tabItem(
tabName = "Out1",
fluidRow(column(width = 10, strong("Data")), align = "center"),
br(),
fluidRow(rpivotTableOutput("Data1"))
)
)
)
)
server <-
function(input, output){
#library(rpivotTable)
output$Data1 <-
renderRpivotTable(
rpivotTable(
data = mtcars
, rows = "cyl"
, cols = "gear"
, height = "780px"
)
)
observeEvent(input$btnExport,{
runjs(
"
var tblhtml=document.getElementsByClassName('pvtRendererArea')[0].innerHTML;
console.log(tblhtml)
//set shiny Input value to read reactively from R
Shiny.setInputValue('tblvar_shiny', tblhtml);
"
)
} )
#save pivot table to html file
# observeEvent(input$tblvar_shiny,
# { write_file(sprintf("<html><body> %s </body></html>",
# input$tblvar_shiny),
# file = "000pivothtml.html" )})
#save pivot table to xls file
observeEvent(input$tblvar_shiny,
{
minimal_html(input$tblvar_shiny) %>%
html_element("table") %>%
html_table() %>%
as.data.frame() %>%
write.xlsx2(file="000pivot_final.xls")
})
}
runApp(
list(ui = ui, server = server) , launch.browser = TRUE
)