【问题标题】:Read a Data Frame into a Separate Function from Shiny将数据框从 Shiny 中读取到单独的函数中
【发布时间】:2018-03-23 07:48:32
【问题描述】:

我有一个 Shiny 应用程序,它允许用户上传 CSV 来进行情绪分析。

目标:

我想使用 Shiny 上传 CSV,然后使用单独的函数 (CapSent) 进行分析并输出结果。

基本上,我试图将用户上传的“df”传递给 Shiny 的函数“CapSent”(位于 global.R 中)。 CapSent 使用自定义词典进行情绪分析。

到目前为止我的代码:

到目前为止我有:

用户界面:

library(shiny)
source('global.R')
ui <- fluidPage(

    sidebarPanel(

            # Input: Select a file ----
            fileInput("file1", "Choose CSV File",
                      multiple = TRUE,
                      accept = c("text/csv",
                                 "text/comma-separated-values,text/plain",
                                 ".csv"))
    ))

服务器:

server <- function(input, output) {

    output$contents <- renderTable({
            req(input$file1)        
            df <- read.csv(input$file1$datapath,
                            header = input$header,
                            sep = input$sep,
                            quote = input$quote)   

            CapSent(0.1, df) # 0.1 represents a threashold, df is the data

            })
    }

shinyApp(ui, server)

函数.R:

CapSent <- function(0.1, df){

    newdf<-data.frame(df,stringsAsFactors = FALSE)

    #....Do some sentiment analysis here on newdf

    #....Then export the sentiment analysis results
    write.csv(newdf,"myResults.csv")

}

问题

使用上面的代码,我收到错误“编码错误

当我手动将“df”添加到全局环境(使用 readr)时,“CapSent”有效,但我希望用户上传自己的数据进行分析。因此问题是:

有没有办法将 df 从 Shiny 传递给 Global Environment?

任何建议将不胜感激。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    试试这个:

    ui.R

    library(shiny)
    
    # Define UI for app that draws a histogram ----
    ui <- fluidPage(
    
      # App title ----
      titlePanel("Hello Shiny!"),
    
      # Sidebar layout with input and output definitions ----
      sidebarLayout(
    
        # Sidebar panel for inputs ----
        sidebarPanel(
    
          # Input:  ----
          fileInput("file1", "Choose CSV File",
                    multiple = TRUE,
                    accept = c("text/csv",
                               "text/comma-separated-values,text/plain",
                               ".csv")),
          actionButton("button", "Apply function/download df"),
          hr(),
          uiOutput("downloadButton")
    
        ),
    
        # Main panel for displaying outputs ----
        mainPanel(
    
          h2("ORIGINAL DATA FRAME"),
          DT::dataTableOutput("contents"),
          br(),
          uiOutput("modify")
    
    
        )
      )
    )
    

    server.R

    server <- function(input, output) {
    
      temp_df <- reactiveValues(df_data = NULL)
      temp_df2 <- reactiveValues(df_data = NULL)
    
    
    
       output$contents <- DT::renderDataTable({
    
          req(input$file1)
          temp_df$df_data <- read.csv(input$file1$datapath, sep = ";")
    
          temp_df$df_data
    
      }, options = (list(pageLength = 5, scrollX = TRUE)))
    
      output$contents2 <- DT::renderDataTable({
    
        temp_df2$df_data
    
    
      }, options = (list(pageLength = 5, scrollX = TRUE)))
    
      observeEvent(input$button,{
        if(!is.null(temp_df$df_data)){
          temp_df2$df_data <- CapSent(temp = 0.7, temp_df$df_data)
    
          output$modify <- renderUI({
            tagList(
              h2("MODIFY DATA FRAME"),
               DT::dataTableOutput("contents2")
             )
          })
    
          output$downloadButton <- renderUI({
             downloadButton("downloadData", "Download")
          })
         }else{
          showNotification("No data was upload")
         }
    
      })
    
    
    
      output$downloadData <- downloadHandler(
    
        filename = function() { 
          paste("data-", Sys.Date(), ".csv", sep="")
        },
        content = function(file) {
          write.csv(temp_df2$df_data, file)
        })
    
    }
    

    由于我不知道 CapSent 的最终用途,我将 CapSent 设为在原始数据框中添加新列的函数;

    global.R

    CapSent <- function(temp = 0.1, df){
    
      newdf <- df
      newdf$New_Col <- temp
      return(newdf)
      #....Do some sentiment analysis here on newdf
    
      #....Then export the sentiment analysis results
      #write.csv(newdf,"myResults.csv")
    
    }
    

    【讨论】:

      【解决方案2】:

      如果您想创建一个全局函数/变量,只需创建一个 global.R,它可以让您在 ui.R 或 server.R 的任何地方使用该函数/变量。

      这是了解更多信息的链接:https://shiny.rstudio.com/articles/scoping.html

      编辑:如果要显示 CSV,首先您需要制作一个标签面板,然后使用 csv 数据制作一个表格,例如:

      使用包DT,install.packages("DT),是制作动态表的包。

      `output$yourtabpanelid = DT::renderDataTable({
            req(input$file1)
      
            df <- read.csv(input$file1$datapath,
                           header = input$header,
                           sep = input$sep,
                           quote = input$quote)
              return(df)
          })`
      

      然后不要创建functions.R,只需将函数放在函数下方并将read.csv(.....)放在函数之前,以便在server.R的所有函数中使用它,例如:

      `df <- read.csv(input$file1$datapath,
                               header = input$header,
                               sep = input$sep,
                               quote = input$quote
      

      ) 服务器

      你可以退出函数 DT 的 df

      【讨论】:

      • 感谢您的回复,但是链接并没有真正解释为什么代码不会触发。我已将脚本更改为 global.R,但仍然没有得到任何输出?
      • 你想展示什么以及你想用 myFunction() 做什么
      • 如果您对该答案有疑问或需要其他结果,请告诉我,我会尽力解决的
      • 再次感谢,我试图澄清我上面的原始问题。您将看到 myFunction() 现在是 CapSent(),它对上传的 csv 进行情绪分析。如您所见,我只是从 Shiny 开始,所以可能没有正确设置它。感谢您在这方面的时间。
      猜你喜欢
      • 2018-11-09
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      相关资源
      最近更新 更多