【发布时间】:2020-04-02 17:53:05
【问题描述】:
我在下面有一个闪亮的应用程序,它可以下载 shapefile。该应用程序运行良好,直到我添加了if else 条件并收到unexpected token ',' 通知。为什么会这样?如果我删除 , 我得到:
Error in shinysession$registerDownload: argument "content" is missing, with no default
如果我离开它,应用程序根本无法运行。
require(shiny)
require(sp)
require(rgdal)
Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe")
runApp(
list(
ui = bootstrapPage(
fileInput('inputdata', 'Input file',accept=c('.csv')),
selectInput("select", label = "Choose a dataset",
choices = c("Tree" , "Crowns"),
selected = "Tree"),
downloadButton('downloadShp', 'DownloadSHP')
),
server = function(input, output) {
createShp <- reactive({
myXY <- input$inputdata
if (is.null(myXY)){
return(NULL)
} else {
xyPoints <- read.table(myXY$datapath, sep=",", header=T)
SHP <- SpatialPointsDataFrame(coords= cbind(xyPoints[,1:2]), data = xyPoints)
proj4string(SHP) <- CRS("+init=epsg:4326")
return(SHP)
}
})
output$downloadShp <- downloadHandler(
if(input$select=="Tree"){
filename = function() { paste0("shpExport.zip") }, #paste('shpExport.zip',
content = function(file) {
if (length(Sys.glob("shpExport.*"))>0){
file.remove(Sys.glob("shpExport.*"))
}
writeOGR(createShp(), dsn="shpExport.shp", layer="shpExport", driver="ESRI Shapefile")
zip(zipfile='shpExport.zip', files=Sys.glob("shpExport.*"),zip = Sys.getenv("R_ZIPCMD", "zip"))
file.copy("shpExport.zip", file)
if (length(Sys.glob("shpExport.*"))>0){
file.remove(Sys.glob("shpExport.*"))
}
}
}
else{
filename = function() { paste0("shpExport2.zip") }, #paste('shpExport.zip',
content = function(file) {
if (length(Sys.glob("shpExport2.*"))>0){
file.remove(Sys.glob("shpExport2.*"))
}
writeOGR(createShp(), dsn="shpExport2.shp", layer="shpExport2", driver="ESRI Shapefile")
zip(zipfile='shpExport2.zip', files=Sys.glob("shpExport2.*"),zip = Sys.getenv("R_ZIPCMD", "zip"))
file.copy("shpExport2.zip", file)
if (length(Sys.glob("shpExport2.*"))>0){
file.remove(Sys.glob("shpExport2.*"))
}
}
}
)
})
)
【问题讨论】:
-
旁白:(1)虽然不是很大,但您正在运行每个
Sys.glob两次。考虑if (length(glb <- Sys.glob("...")) > 0) file.remove(glb)(名称glb是任意的)。 (2) 你应该几乎总是使用library,而不是require。当包不可用时,后者永远不会停止跟踪代码,这几乎不是预期的。参考:stackoverflow.com/a/51263513. -
是的,但为什么会发生原始 Q 中的问题。这很奇怪。代码在没有 if() 的情况下工作
标签: r if-statement shiny download