18

我有一张地图传单,我想将其保存在特定文件夹中的 html 文件中。我正在使用 Windows 7。

我尝试了以下方法:

library(htmlwidgets)
saveWidget(map_leaflet, file="ressources/test.html")

library(htmlwidgets)
saveWidget(map_leaflet, file="ressources\\test.html")

library(htmlwidgets)
path_name <- file.path("ressources", "test.html", fsep="\\")
saveWidget(map_leaflet, file=path_name)

library(htmlwidgets)
path_name <- paste("ressources", "test.html", sep="/")
saveWidget(map_leaflet, file=path_name)

作为错误消息,根据 Rstudio 会话,我要么有

1) setwd(dir) 中的错误:无法更改工作目录

2) 找不到路径

当我只保存这样的:

library(htmlwidgets)
saveWidget(map_leaflet, file="test.html")

它完美地工作。

预先感谢您的帮助。

4

2 回答 2

22

同意。

这是一种解决方法:

f<-"ressources\\test.html"
saveWidget(map_leaflet,file.path(normalizePath(dirname(f)),basename(f)))

问题似乎是 saveWidget 不适用于相对路径名,而 normalizePath 不适用于已经存在的文件的路径。

我将其称为 saveWidget 中的错误。

编辑:

我为现有的未解决问题贡献了我认为更好的解决方法

于 2017-07-20T06:30:53.777 回答
0

我使用包中的with_dir函数withr来执行此操作。我也把它放在一个包装函数中:

save_leaflet <- function(plot, file, overwrite = FALSE){
  # save the file if it doesn't already exist or if overwrite == TRUE
  if( !file.exists(file) | overwrite ){
    withr::with_dir(new = dirname(file), 
                    code = htmlwidgets::saveWidget(plot, 
                                                   file = basename(file)))
  } else {
    print("File already exists and 'overwrite' == FALSE. Nothing saved to file.")
  }
}
于 2020-10-29T18:33:02.947 回答