R Shiny 请求用户选择目录
Posted
技术标签:
【中文标题】R Shiny 请求用户选择目录【英文标题】:R Shiny request user to choose directory 【发布时间】:2014-10-18 09:23:24 【问题描述】:我是 R 和 R Shiny 的新手。
对于我目前需要手动输入文件名的代码,我想概括一下,让用户选择工作目录和相应的文件名。
1、用户选择工作目录
然后闪亮能够将所有文件名存储在选定的工作目录下。类似于list.files()
2,那么box list files会列出选中wd下的所有文件名 并且用户可以检查应该显示哪个数据集
3、在主面板中 将显示带有标题的数据集的前 10 个实例
我试过的是
服务器.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)
)
)
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")
)
)
))
情况类似于This website,而我的情况是请求用户选择本地工作目录。
感谢您的温柔帮助
【问题讨论】:
一个好的问题不仅包含一般任务描述,还包含解决任务所采取的步骤以及具体失败的地方。 【参考方案1】:首先,创建.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)
在您的应用中添加 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)
然后,您只需对提供给我们的原始脚本进行一些更改。在 ui.R 中,我将重新定义 selectInput
函数,以便向用户显示文件的名称。此外,您不能确定所选文件夹是否有 2 个文件。
selectInput("dataset", "Choose a dataset:",
choices = list_of_datasets)
在 server.R 中,您应该 i) 删除第 2、3 和 4 行(已由 global.R 处理)并 ii) 更改 datasetInput
函数:
datasetInput <- reactive(
files[[as.numeric(input$dataset)]]
)
【讨论】:
以上是关于R Shiny 请求用户选择目录的主要内容,如果未能解决你的问题,请参考以下文章
如何根据 Shiny R 中的用户选择在 MainPanel 中显示数据?