问题 来自R中的htmlwidget的savewidget,无法将html文件保存在另一个文件夹中


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

它完美地运作。

预先感谢您的帮助。


9616
2017-12-30 16:56


起源

它听起来像目录 ressources 从执行代码的位置不存在。你试过检查吗? getwd() 在运行此代码之前的R中,以确保从正确的目录运行它,并且 dir() 确保这一点 ressources 存在于那个位置?如果这两个看起来都正确,则可能使用不太有利的解决方案 setwd("ressources") 在尝试保存之前更改到该目录。 - user5359531
嗨,所以我尝试了getwd()和dir(),并且ressources确实正确显示。然后我尝试了这个 path <- file.path(getwd(), "ressources", "test.html")  saveWidget(map_leaflet, file=path) 这次它完美无缺。我想它只需要完整的路径。您可以将评论作为答案,以便我可以将问题标记为已回答吗?谢谢 - tuttifolies
我的提示只是故障排除。听起来你似乎没有从你认为自己所处的位置执行代码。但正如您所发现的那样,使用完整路径并使用 file.path() 更安全地传递路径的方法。你可能也想看看 normalizePath() 功能。它可以帮助您获得绝对路径,并且还可以让您知道路径是否不存在或不正确。试试这些,你会看到: normalizePath("."), normalizePath("~"), normalizePath("./foo") < - 如果出错将会出错 foo 不存在。您也可能只是无法使用相对路径 file= - user5359531


答案:


同意。

这是一个解决方法:

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

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

我将此称为saveWidget中的错误。

编辑:

我已经贡献了我认为更好的解决方法 现有的公开问题


9
2017-07-20 06:30