r - 检查两个路径是否解析到同一个目录
问题描述
在检查两个文件路径是否解析为同一个文件时,解决方案是使用normalizePath
;但是,这对于目录似乎不是确定的:
td1 <- tempdir()
td2 <- paste0(td1, "/")
dir.exists(td1) && dir.exists(td2)
#> [1] TRUE
file.create(file.path(td1, "foo.txt"))
#> [1] TRUE
file.exists(file.path(td2, "foo.txt"))
#> [1] TRUE
normalizePath(td1) == normalizePath(td2)
#> [1] FALSE
sessionInfo()
#> R version 3.5.1 (2018-07-02)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 17134)
#>
#> Matrix products: default
#>
#> locale:
#> [1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252
#> [3] LC_MONETARY=English_Australia.1252 LC_NUMERIC=C
#> [5] LC_TIME=English_Australia.1252
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> loaded via a namespace (and not attached):
#> [1] compiler_3.5.1 backports_1.1.2 magrittr_1.5 rprojroot_1.3-2
#> [5] tools_3.5.1 htmltools_0.3.6 yaml_2.2.0 Rcpp_0.12.18
#> [9] stringi_1.1.7 rmarkdown_1.10 knitr_1.20 stringr_1.3.1
#> [13] digest_0.6.16 evaluate_0.11
由reprex 包(v0.2.0) 于 2018 年 9 月 5 日创建。
在识别目录方面是否有可靠(或更可靠)的方法?
解决方案
如果您愿意为此使用一个包,那么我在fs包中获得了很大的成功,用于跨操作系统稳健的路径操作。例如,当它通过 规范化时fs::path_norm()
,它将在 Windows 上去除这个尾部斜杠。
td1 <- tempdir()
td2 <- paste0(td1, "/")
dir.exists(td1) && dir.exists(td2)
#> [1] TRUE
file.create(file.path(td1, "foo.txt"))
#> [1] TRUE
file.exists(file.path(td2, "foo.txt"))
#> [1] TRUE
normalizePath(td1) == normalizePath(td2)
#> [1] FALSE
library(fs)
path_norm(td1) == path_norm(td2)
#> [1] TRUE
sessionInfo()
#> R version 3.4.3 (2017-11-30)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 17134)
#>
#> Matrix products: default
#>
#> locale:
#> [1] LC_COLLATE=English_United States.1252
#> [2] LC_CTYPE=English_United States.1252
#> [3] LC_MONETARY=English_United States.1252
#> [4] LC_NUMERIC=C
#> [5] LC_TIME=English_United States.1252
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> loaded via a namespace (and not attached):
#> [1] compiler_3.4.3 backports_1.1.2 magrittr_1.5 rprojroot_1.3-2
#> [5] tools_3.4.3 htmltools_0.3.6 yaml_2.1.16 Rcpp_0.12.18
#> [9] stringi_1.1.6 rmarkdown_1.8 knitr_1.17 stringr_1.2.0
#> [13] digest_0.6.16 evaluate_0.10.1
由reprex 包(v0.2.0) 于 2018 年 9 月 5 日创建。
推荐阅读
- swift - 更改 UISearchBar 的文本字段字体也会更改它的高度
- sql - PLSQL 中的时间戳过滤器
- reactjs - 如何从 react-native-video 中删除底部控件
- android - 如何在 kotlin 中使用意图将图像共享到另一个应用程序?
- google-cloud-platform - 如何在 Google Cloud Logs Explorer 中查询 VM 合规性报告
- java - 如何使我的应用与华为商店兼容?
- class - 如何安装importcalss
- c# - 如何从所有商店获得所有销售额?
- python - 使用 fbProphet 交叉验证的 Broken Process Pool 错误
- git - 什么是“本地 Git 客户端”