【问题标题】:savewidget from htmlwidget in R , cannot save html file in another folder来自 R 中 htmlwidget 的 savewidget,无法将 html 文件保存在另一个文件夹中
【发布时间】:2017-05-14 23:09:22
【问题描述】:

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

效果很好。

提前感谢您的帮助。

【问题讨论】:

  • 从执行代码的位置听起来好像目录ressources 不存在。您是否在运行此代码之前尝试在 R 中检查 getwd() 以确保您从正确的目录运行它,并检查 dir() 以确保 ressources 存在于该位置?如果这两个看起来都正确,一个不太有利的解决方案可能是在尝试保存之前使用setwd("ressources") 更改到该目录。
  • 您好,所以我尝试了 getwd() 和 dir() 并且 ressources 确实显示正确。然后我尝试了这个path &lt;- file.path(getwd(), "ressources", "test.html")saveWidget(map_leaflet, file=path),这一次它工作得很好。我想它只需要完整的路径。您能否发表评论作为答案,以便我可以将问题标记为已回答?谢谢
  • 我的提示只是排除故障。听起来您仍然没有从您认为的位置执行代码。但正如您所发现的,使用完整路径和使用file.path() 是安全通过路径的更可靠方法。您可能还想查看normalizePath() 函数。它可以帮助您获取绝对路径,也可以让您知道路径是否不存在或不正确。试试这些,你会看到:normalizePath(".")normalizePath("~")normalizePath("./foo") foo 不存在,会报错。此外,您可能根本无法使用 file= 的相对路径

标签: html r save htmlwidgets


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    同意。

    这里有一个解决方法:

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

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

    我认为这是 saveWidget 中的一个错误。

    编辑:

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

    【讨论】:

      猜你喜欢
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 2021-12-25
      • 2019-09-02
      • 1970-01-01
      • 2014-09-18
      相关资源
      最近更新 更多