来自htmlwidget的savewidget在R中,无法将html文件保存在其他文件夹中

来自htmlwidget的savewidget在R中,无法将html文件保存在其他文件夹中,html,r,save,htmlwidgets,Html,R,Save,Htmlwidgets,我有一个地图传单,我想保存在一个特定文件夹中的html文件中。 我正在使用Windows7 我尝试了以下方法: library(htmlwidgets) saveWidget(map_leaflet, file="ressources/test.html") library(htmlwidgets) saveWidget(map_leaflet, file="ressources\\test.html") library(htmlwidgets) path_name <- file.p

我有一个地图传单,我想保存在一个特定文件夹中的html文件中。 我正在使用Windows7

我尝试了以下方法:

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)
它工作得很好

提前感谢您的帮助。

同意

以下是一个解决方法:

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

f我使用
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.")
  }
}

save\u传单听起来好像执行代码的位置不存在目录
resources
。在运行此代码之前,是否尝试在R中检查
getwd()
,以确保从正确的目录运行,以及
dir()
以确保
resources
存在于该位置?如果这两种方法看起来都正确,那么一个不太好的解决方案可能是在尝试保存之前使用
setwd(“resources”)
更改到该目录。您好,所以我尝试了getwd()和dir(),resources确实显示正确。然后我尝试了这个
路径,我的提示只是故障排除。听起来好像你并没有从你认为的地方执行代码。但正如您所发现的,使用完整路径和使用
file.path()
是安全通过路径的更可靠的方法。您可能还想看看
normalizePath()
函数。它可以帮助您获得绝对路径,还可以让您知道路径是否不存在或不正确。尝试这些,您将看到:
normalizePath(“.”
normalizePath(“~”
normalizePath(“/foo”)
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.")
  }
}