首页 > 解决方案 > 如何使用 Reticulate 在 R shiny App 中导入 Python 函数以供下载 App

问题描述

data_xi <- data.frame(s = c(1:3),r = c(4:6), x =c(19:21))我想在我的function.py文件中使用python函数,并且有一个名为run_xi的函数,它只是从数据库中提取数据并将数据框返回给R。但是,如果我替换,这段代码可以成功运行使用 reticulate 的代码(如下代码所示),它将无法生成 csv 文件,只返回一个 HTML 文件。有什么解决办法吗?

library(shiny)
library(reticulate)
library(writexl)

#reticulate::source_python("function.py")
#data_xi <- run_xi(26)

if (interactive()) {

  ui <-fluidPage(
    downloadButton("downloadData", "Download Metrics Reports")
  )

  #data_xi <- data.frame(s = c(1:3),r = c(4:6), x =c(19:21)) # uncomment here, code will working
  reticulate::source_python("function.py") # not working when try to use python function by reticulate
  data_xi <- run_xi(26)# not working when try to use python function by reticulate
  server <- function(input,output){



    output$downloadData <- downloadHandler(

      filename = function(){
        paste(Sys.time(), 'site_mtx.xlsx')
      },

      content = function(file){
        write_xlsx(data_xi, file)
      }
    )
  }

  shinyApp(ui, server)}

标签: rshinyappsreticulate

解决方案


我已经解决了这个问题,我使用 reticulate 函数创建了另一个 R 函数来导入 python 函数,然后在服务器中使用source直接导入 r 函数,然后它可以下载为 Excel 而不是 html


推荐阅读