gpt4 book ai didi

r - 从 Shiny 下载形状文件

转载 作者:行者123 更新时间:2023-12-04 12:48:53 24 4
gpt4 key购买 nike

我有一个 Shiny 的应用程序,它读取 gpx 轨迹文件并对其进行缓冲。然后我希望用户能够将该 shapefile 下载到他们选择的目的地。我一直在尝试使用 downloadHandler 函数,但到目前为止我并不喜欢。

我创建的 shapefile 的名称叫做 trk_buff。在 R 中我可以使用:

my_dsn<-"C:\\Documents\\TrackFiles"
writeOGR(obj=trk_buff, dsn=my_dsn, layer="BufferedTracks", driver="ESRI Shapefile")

我尝试过这样使用 downloadHandler:

  output$downloadData<-downloadHandler(
filename=function(file){trk_buff},
content=function(file){
writeOGR(obj=trk_buff, dsn=file, layer="BufferedTracks", driver="ESRI Shapefile")
})

但我显然做错了什么,因为没有任何反应......:|

编辑添加如果我使用 Action 按钮和文本文件框的组合,我可以获得我想要的行为。但这有点笨拙,涉及用户显式写入文件路径而不是搜索它,这可能会导致错误:例如在 ui.R 中我有:

textInput("filepath","Filepath to download data"),
actionButton("act1","Download shapefile")

在 server.R 我有:

  action_btn_code <- eventReactive(input$act1, {
file_path<-input$filepath
writeOGR(obj=trk_buff, dsn=paste(file_path,"/Tracks",sep=""), layer="BufferedTracks",
driver="ESRI Shapefile", overwrite_layer=TRUE)
})

最佳答案

以下对我有用。这个想法是您必须压缩 shapefile,因为 downloadHandler 只能处理一个文件的下载。

output$download_shp <- downloadHandler(
filename = "shapefile.zip",
content = function(file) {
data = trk_buff() # I assume this is a reactive object
# create a temp folder for shp files
temp_shp <- tempdir()
# write shp files
writeOGR(data, temp_shp, "trk_buff", "ESRI Shapefile",
overwrite_layer = TRUE)
# zip all the shp files
zip_file <- file.path(temp_shp, "trk_buff_shp.zip")
shp_files <- list.files(temp_shp,
"trk_buff",
full.names = TRUE)
# the following zip method works for me in linux but substitute with whatever method working in your OS
zip_command <- paste("zip -j",
zip_file,
paste(shp_files, collapse = " "))
system(zip_command)
# copy the zip file to the file argument
file.copy(zip_file, file)
# remove all the files created
file.remove(zip_file, shp_files)
}
)

关于r - 从 Shiny 下载形状文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41707760/

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