gpt4 book ai didi

R Shiny : Uploading a file on button click

转载 作者:行者123 更新时间:2023-12-04 08:09:15 25 4
gpt4 key购买 nike

我知道网上已经有很多 Material 可以回答我的问题,但似乎没有一个对我有用。我想那是因为我不太了解 Shiny 的响应式(Reactive)编程。

所以,我希望创建一个界面,让用户使用 fileInput 选择文件。并仅在单击“上传”按钮时上传它。我尝试了各种论坛的一些解决方案,但都没有奏效。以下是我最近的尝试:

#ui.R

library(shiny)

shinyUI(pageWithSidebar(


headerPanel(""),

sidebarPanel(

fileInput("in_file", "Input file:",
accept=c("txt/csv", "text/comma-separated-values,text/plain", ".csv")),
checkboxInput(inputId="is_header", label="Does the input file have column names?", value=TRUE),
actionButton("upload_data", "Upload Data"),
),
mainPanel(
tabsetPanel(
tabPanel("Original Data", tableOutput("orig_data"))
)
)
))


#server.R

library(shiny)

shinyServer(function(input, output, session) {

ra_dec_data <- reactive({
if(input$upload_data==0)
return(NULL)

return(isolate({
head(read_data(input$in_file$datapath, input$in_file$is_header), 50)
}))
})

output$orig_data <- renderTable({
ra_dec_data()
})
})

我面临的问题是文件一被选中就会被上传,而“上传”按钮没有响应。

我的猜测是我所做的没有意义,所以请接受我为做这件事而道歉。任何帮助将非常感激。谢谢!

最佳答案

fileInput直接上传文件,所以我建议您创建自己的“fileInput”。

这是我将如何进行:

服务器端

library(shiny)

shinyServer(function(input, output, session) {

observe({

if (input$browse == 0) return()

updateTextInput(session, "path", value = file.choose())
})

contentInput <- reactive({

if(input$upload == 0) return()

isolate({
writeLines(paste(readLines(input$path), collapse = "\n"))
})
})

output$content <- renderPrint({
contentInput()
})

})

用户界面
library(shiny)

shinyUI(pageWithSidebar(

headerPanel("Example"),

sidebarPanel(
textInput("path", "File:"),
actionButton("browse", "Browse"),
tags$br(),
actionButton("upload", "Upload Data")
),

mainPanel(
verbatimTextOutput('content')
)

))

在“Server.R”中,每次单击“浏览”操作按钮时,我们首先更新文本输入的值。

“contentInput”是一个响应式函数,它会在输入值(包含在函数体中)改变时重新执行,这里是“input$upload”,而不是当“input$path”改变时,因为我们隔离了它。如果我们不隔离包含“input$path”的部分,每次浏览新文件时都会重新执行“contentInput”,这样上传按钮在这里就没有用了。

然后我们在“output$content”中返回“contentInput”的结果。

希望这有帮助。

编辑 ## :

我意识到如果你取消选择它的文件会产生错误并且 Shiny 的应用程序崩溃,那么你应该使用 Henrik Bengtsson ( https://stat.ethz.ch/pipermail/r-help/2007-June/133564.html ) 的这个函数:
file.choose2 <- function(...) {
pathname <- NULL;
tryCatch({
pathname <- file.choose();
}, error = function(ex) {
})
pathname;
}

关于R Shiny : Uploading a file on button click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21813773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com