R 中 html 小部件的保存小部件,无法将 html 文件保存在另一个文件夹中

savewidget from htmlwidget in R , cannot save html file in another folder

我有一张地图传单,我想将其保存在特定文件夹中的 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")

效果很好。

预先感谢您的帮助。

同意。

这里有一个解决方法:

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

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

我认为这是 saveWidget 中的错误。

编辑:

我已经贡献了我认为更好的解决方法 an existing open issue

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

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