R Shiny请求用户选择目录

use*_*seR 10 r shiny

我是R和R Shiny的新手.

对于我现在需要手动输入文件名的代码,我想概括一下这个案例并让用户选择工作目录和相应的文件名.

1,用户选择工作目录然后闪亮能够存储所选工作目录下的所有文件名.相近list.files()

2,然后框列表文件将列出所选wd下的所有文件名,用户可以检查应显示哪个数据集

3,在主面板中,将显示带有标题的数据集的前10个实例

我试过的是

server.R

library(shiny)
setwd("C:/Users/HKGGAIT001/Google Drive/GA Project/Cargo/Cargo.Statistics/data/Hactl")
data1 <- read.csv(list.files()[1])
data2 <- read.csv(list.files()[2])

# Define server logic required to summarize and view the selected
# dataset
shinyServer(function(input, output) {

  # Return the requested dataset
  datasetInput <- reactive({
    switch(input$dataset,
           "data1" = data1,
           "data2" = data2)
  })

  # Generate a summary of the dataset
  output$summary <- renderPrint({
    dataset <- datasetInput()
    summary(dataset)
  })

  # Show the first "n" observations
  output$view <- renderTable({
    head(datasetInput(), n = input$obs)
  })
})
Run Code Online (Sandbox Code Playgroud)

ui.R

library(shiny)

# Define UI for dataset viewer application
shinyUI(fluidPage(

  # Application title
  titlePanel("Shiny Text"),

  # Sidebar with controls to select a dataset and specify the
  # number of observations to view
  sidebarLayout(
    sidebarPanel(
      selectInput("dataset", "Choose a dataset:", 
                  choices = c("data1", "data2")),

      numericInput("obs", "Number of observations to view:", 10)
    ),

    # Show a summary of the dataset and an HTML table with the 
     # requested number of observations
    mainPanel(
      verbatimTextOutput("summary"),

      tableOutput("view")
    )
  )
))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

情况类似于本网站,而我的情况是请求用户选择本地工作目录.

谢谢你的温柔帮助

Tom*_*los 2

首先,创建.csv可重复性的文件:

write.csv(x = data.frame(V1 = 1:13, V2 = letters[1:13]),
          file = "teste1.csv", row.names = FALSE)

write.csv(x = data.frame(V1 = 14:26, V2 = letters[14:26]),
          file = "teste2.csv", row.names = FALSE)

write.csv(x = data.frame(V1 = rnorm(15), V2 = runif(15)),
          file = "teste3.csv", row.names = FALSE)
Run Code Online (Sandbox Code Playgroud)

在您的应用程序中添加global.R脚本可能会很有用。在此脚本中,您将能够:

我。让用户选择工作目录,

二. 读取.csv该文件夹中的文件,

三. 创建可由 ui.R 和 server.R 使用的文件列表

# global.R
library(shiny)

wd <<- choose.dir()
setwd(wd)

csv <<- list.files(pattern = ".csv")

files <<- vector("list", length(csv))
for (i in seq_along(files)) {
  files[[i]] <- read.csv(csv[i], stringsAsFactors = FALSE)
}

list_of_datasets <<- seq_along(files)
names(list_of_datasets) <- gsub(pattern = ".csv", replacement = "", x = csv)
Run Code Online (Sandbox Code Playgroud)

然后您只需对您提供给我们的原始脚本进行一些更改即可。在ui.R中,我将重新定义该selectInput函数,以便向用户显示文件的名称。另外,您无法确定所选文件夹是否包含 2 个文件。

selectInput("dataset", "Choose a dataset:", 
            choices = list_of_datasets)
Run Code Online (Sandbox Code Playgroud)

server.R中,您应该 i) 删除第 2、3 和 4 行(已由 global.R 处理)和 ii) 更改datasetInput函数:

datasetInput <- reactive({
  files[[as.numeric(input$dataset)]]
})
Run Code Online (Sandbox Code Playgroud)