tmap::save_tmap 函数无法将 HTML 文件保存在工作目录以外的文件夹中

tmap::save_tmap function cannot save HTML file in folders other than the working directory

我正在学习如何使用 tmap 包生成地图并将其保存到交互式 HTML 文件中。如果我创建了一个 tmap 对象并使用 save_tmap 函数将其保存到我的工作目录,我将按预期得到一个 HTML 文件。但是,如果我将目录更改为其他路径,则会生成一条错误消息。请看下面的例子。

# Load tmap package
library(tmap)
# Load example data
data(World)
# Create example map
example_map <- tm_shape(World, projection="longlat") + 
      tm_polygons() + 
      tm_layout("Long lat coordinates (WGS84)", 
                inner.margins = c(0, 0, .1, 0), title.size = .8)

# Save an HTML object
save_tmap(example_map, "example_map.html")

我将在我的工作目录中获取 example_map.html

# Create a folder in the working directory
if (!dir.exists("tmap_folder")){
  dir.create("tmap_folder")
}

# Save the HTML object in "tmap_folder"
save_tmap(example_map, "tmap_folder/example_map.html")

不行。我将收到以下错误消息

Error in normalizePath(path.expand(path), winslash, mustWork) : path[1]="tmap_folder": The system cannot find the file specified

如果您对导致此错误的原因有任何想法,请分享您的想法。

这听起来像是 normalizePath 和 Windows 之间的较量(参见另一个示例 here)。不要使用像 "tmap_folder/example_map.html" 这样的相对路径,而是尝试使用像 C:/users/ycw/tmap_folder/example_map.html.

这样的绝对路径

另一个选项似乎是使用 here 包。这样,您不必指定完整路径,并且您的代码可能更便携,可以更好地与 rstudio 项目和 Rmarkdown 一起玩。

# Save the HTML object in "tmap_folder" with here package
library(here)
save_tmap(example_map, here("tmap_folder","example_map.html"))