R+Shiny:读取文件并使用其内容

R+Shiny: read file and use its content

请在下面找到我在网上找到的脚本示例(可能来自 Rstudio),用于创建一个简单的应用程序来读取各种平面文件并输出 table。 我添加了一些创建应用程序可以读取的文件“test_input_file.csv”。

我迷失了一个非常简单的任务:读取 csv 文件后,我有一个 tibble 并将其渲染为 table。我如何直接访问此 tibble 以用它做其他事情?例如。用 plotly 绘制它,进行一些统计等......? 非常感谢

library(shiny)
library(tidyverse)


tt <- tibble(AA=seq(10), BB=seq(10)*2, CC=seq(10)*3 )

write_csv(tt, "test_input_file.csv")

rm(tt)

# Define UI for data upload app ----
ui <- fluidPage(

  # App title ----
  titlePanel("Uploading Files"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

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

      # Horizontal line ----
      tags$hr(),

      # Input: Checkbox if file has header ----
      checkboxInput("header", "Header", TRUE),

      # Input: Select separator ----
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t",
                               Space = " "),
                   selected = ","),

      # Input: Select quotes ----
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"'),

      # Horizontal line ----
      tags$hr(),

      # Input: Select number of rows to display ----
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")

    ),

    # Main panel for displaying outputs ----
    mainPanel(

      # Output: Data file ----
      tableOutput("contents")

    )

  )
)

# Define server logic to read selected file ----
server <- function(input, output) {

  output$contents <- renderTable({

    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, head of that data file by default,
    # or all rows if selected, will be shown.

    req(input$file1)

    # when reading semicolon separated files,
    # having a comma separator causes `read.csv` to error
    tryCatch(
      {
        df <- read.csv(input$file1$datapath,
                 header = input$header,
                 sep = input$sep,
                 quote = input$quote)
      },
      error = function(e) {
        # return a safeError if a parsing error occurs
        stop(safeError(e))
      }
    )

    if(input$disp == "head") {
      return(head(df))
    }
    else {
      return(df)
    }

  })

}

# Create Shiny app ----
shinyApp(ui, server)
#> PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
静态 R Markdown 文档不支持闪亮的应用程序

reprex package (v2.0.1)

于 2022-03-09 创建

此代码将文件直接加载到输出 table 中,并没有真正将原始 table 存储在任何地方。这段代码实际上是在加载文件:

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

您可以在 renderTable({}) 的 外部 使用它来加载文件,就像普通变量一样,并用它做任何您想做的事。

但是,如果您将此代码直接设置到服务器函数中,它将不起作用 - 因为这是用户输入,您应该将此变量设置为反应式,所以我会这样做:

  df = reactive({
    req(input$file1)
    
    df <- read.csv(input$file1$datapath,
                   header = input$header,
                   sep = input$sep,
                   quote = input$quote)
    
    return(df)
  })

然后你可以调用 df() 并用它做任何你想做的事。 Ofc 最好添加 try 语句或一些检查以确保文件可以正确加载,例如 renderTable({}).

所以服务器端应该是这样的:

server <- function(input, output) {
  
  df = reactive({
    req(input$file1)
    
    df <- read.csv(input$file1$datapath,
                   header = input$header,
                   sep = input$sep,
                   quote = input$quote)
    
    return(df)
  })
  
  output$contents <- renderTable({
    
    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, head of that data file by default,
    # or all rows if selected, will be shown.
    
    req(input$file1)
    
    # when reading semicolon separated files,
    # having a comma separator causes `read.csv` to error
    tryCatch(
      {
        df <- read.csv(input$file1$datapath,
                       header = input$header,
                       sep = input$sep,
                       quote = input$quote)
      },
      error = function(e) {
        # return a safeError if a parsing error occurs
        stop(safeError(e))
      }
    )
    
    if(input$disp == "head") {
      return(head(df))
    }
    else {
      return(df)
    }
    
  })
  
}