簡體   English   中英

來自 R 中 htmlwidget 的 savewidget,無法將 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 中的錯誤。

編輯:

我已經為現有的未決問題貢獻了我認為更好的解決方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM