r - If 语句导致闪亮应用程序中的 downloadhandler() 出现问题
问题描述
我在下面有一个闪亮的应用程序,它可以下载 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.*"))
}
}
}
)
})
)
解决方案
downloadHandler
是一个函数,所以它的参数需要是实际参数。你不能做
downloadHandler(
if (condexpr) {
filename = ...,
content = ...
} else {
filename = ...,
content = ...
}
)
这不是合法的 R 语法。
相反,像
downloadHandler(
filename = if (condexpr) func1 else func2,
content = if (condexpr) ... else ...
)
或者
downloadHandler(
filename = function() if (condexpr) expr1 else expr2,
content = function(file) if (condexpr) expr1 else expr2
)
而且由于?downloadHandler
状态
可以从此函数中使用反应值和函数
对于filename=
和content=
参数,您仍然可以(input$select=="Tree")
用作条件。
推荐阅读
- python - 检查对象属性时,if-else 条件始终返回 false
- java - 如果 BigInteger 对于 int 来说太大,如何返回 int?
- outlook-redemption - C# folder.FolderPath(和许多其他动态属性)
- java - Stream api reduce方法在尝试对大数求和时返回负值
- node.js - 如何在数组中获取二级数组并写入ejs文件mongodb nodejs
- c# - 如何在 asp.net 核心中创建具有多个可选字符串参数的路由?
- python - 通过键盘输入的七位数字的校验和
- python-3.x - 如何从特定匹配中提取和创建新列
- python - 根据 pandas 中的条件迭代和求和值
- swift - SwiftUI 移除全屏封面的过渡