r-如何通过闪亮应用程序中的fileInput功能验证csv文件上传



在运行以下程序时;缩写代码";,我试图创建一个文件上传验证,要上传的csv必须具有";场景1";以及";场景1";在csv的单元格A1和B1中。否则该文件不被上传并且被标记为"不上传";无效";。有什么办法吗?

如果您运行以下操作,单击单操作按钮并通过单击模式对话框底部的按钮保存矩阵输入,查看下载的csv,并查看单元格A1和B1如何显示";场景1";以及";场景1";从下载的矩阵。这很好。如果你删除这些并保存csv,你会看到这个修改后的csv在运行应用程序时仍然可以上传。我希望这两个csv字段作为验证标志。

我真的很喜欢try()函数作为这个应用程序中的一个包罗万象的测试。

缩写代码:

library(dplyr)
library(shiny)
library(shinyFeedback)
library(shinyMatrix)
sumMat <- function(x){return(rep(sum(x,na.rm = TRUE), 10))}
ui <- fluidPage(
useShinyFeedback(),
sidebarLayout(
sidebarPanel(
actionButton("matrix3show","Click for matrix input"),
),
mainPanel(plotOutput("plot"))
)
)
server <- function(input, output, session) {

uploadMat3Data <- reactive({
req(input$uploadMat3)
validate(need(identical(tools::file_ext(input$uploadMat3$datapath),"csv"),"Invalid"))
try(read.csv(input$uploadMat3$datapath, header = TRUE))
})

observeEvent(uploadMat3Data(), {
if(is.data.frame(uploadMat3Data())){
updateMatrixInput(session,"matrix3",as.matrix(uploadMat3Data()))
hideFeedback("file")
} 
else {showFeedbackWarning("file", "Invalid")}
})

observeEvent(input$matrix3show,{
showModal(
modalDialog(
fileInput(inputId = "uploadMat3",label = NULL,accept = ".csv"),
matrixInput(
inputId = "matrix3",
value = if(is.null(input$matrix3)){matrix(c(1,5),ncol=2,dimnames=list(NULL,rep("Scenario 1",2)))}
else {input$matrix3},
rows = list(extend = TRUE, delete = TRUE),
cols = list(extend = TRUE, delta = 2, delete = TRUE, multiheader = TRUE),
class = "numeric"),
output$verbMat3 <- renderPrint(class(uploadMat3Data())),
footer = 
tagList(
downloadButton("saveMat3","Save",style = "width:80px;"),
modalButton("Exit box")
) # close tag list
))
})
observeEvent(input$matrix3, {
tmpMat3 <- input$matrix3
colnames(tmpMat3) <- paste("Scenario",rep(1:ncol(tmpMat3),each=2,length.out=ncol(tmpMat3)))
rownames(tmpMat3) <- paste("Row", seq_len(nrow(input$matrix3)))
updateMatrixInput(session,inputId="matrix3",value=tmpMat3)
})

data <- function(){tibble(X = seq_len(10),Y = sumMat(input$matrix3))}  

output$plot<-renderPlot({plot(data(),type="l")})

output$saveMat3 <- downloadHandler(
filename = function(){paste("Inputs","csv",sep=".")},
content = function(file){write.csv(input$matrix3, file,row.names=FALSE)}
)
}
shinyApp(ui, server)

为了解决问题,我将uploadMat3Data()observeEvent更改为以下内容:

observeEvent(uploadMat3Data(), {
if(is.data.frame(uploadMat3Data()) 
&& colnames(uploadMat3Data()[1]) == "Scenario.1"
&& colnames(uploadMat3Data()[2]) == "Scenario.1.1"
){
updateMatrixInput(session,"matrix3",as.matrix(uploadMat3Data()))
hideFeedback("uploadMat3")
} 
else {showFeedbackWarning("uploadMat3", "Invalid")}
})

注意&& colnames(...的添加,其中代码窥探上传数据帧的标头并检查所需的标头。还要注意,在原始代码中,hideFeedback()showFeedbackWarning()中的id引用不正确;它们现在被校正为"0";uploadMat3";

相关内容

  • 没有找到相关文章

最新更新