使用writeogr()下载Shapefile时出现R Shiny downloadHandler()错误

时间:2017-05-17 18:34:17

标签: r shiny

我是R的新手,并创建了一个将CSV文件转换为shapefile的Shiny应用程序。运行我的代码时出现此错误:

enter image description here

我的代码:

runApp(list(
  ui = bootstrapPage(
      fileInput('inputdata', 'Input file',accept=c('.csv')),
      plotOutput("xyPlot"),
      downloadButton('downloadShp', 'DownloadSHP')
       ),
  server = function(input, output) {

  output$xyPlot <-  renderPlot({

  myXY<- input$inputdata
  if (is.null(myXY)) 
    return(NULL)       

  xyPoints<-read.table(myXY$datapath, sep=",", header=T)

  SHP <- SpatialPointsDataFrame(coords= cbind(xyPoints[,1:2]), data =  xyPoints)
  proj4string = CRS('+proj=longlat +datum=NAD83')

  plot(SHP)

  output$downloadShp <- downloadHandler(
    filename = 'fbCrawlExport.zip',
    content = function(file) {
      if (length(Sys.glob("fbCrawl.*"))>0){
        file.remove(Sys.glob("fbCrawl.*"))
      }
      writeOGR(SHP, dsn="fbCrawl.shp", layer="fbCrawl", driver="ESRI Shapefile")
      write.csv(as.data.frame(cbind(SHP@data, as.data.frame(SHP@coords))), "fbCrawl.csv")
      zip(zipfile='fbCrawlExport.zip', files=Sys.glob("fbCrawl.*"))
      file.copy("fbCrawlExport.zip", file)
      if (length(Sys.glob("fbCrawl.*"))>0){
        file.remove(Sys.glob("fbCrawl.*"))
      }
    }
  )

  }) 
 }
 ))

1 个答案:

答案 0 :(得分:2)

我使用Rtools解决了这个问题。 这是我更新的代码

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')),
  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(

    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.*"))
      }
    }
  )

}) 
)