gpt4 book ai didi

r - R中的完全限定文件名

转载 作者:行者123 更新时间:2023-12-04 06:26:49 25 4
gpt4 key购买 nike

给定任何标准符号,我希望在 R 中获得文件的完全限定名称。例如:

  • 文件.ext
  • ~/file.ext (这种情况可由 path.expand 处理)
  • ../current_dir/file.ext

  • 例如,完全限定的文件名是指(在类 Unix 系统上):

    /home/user/some/path/file.ext



    (已编辑 - 使用 file.path 并尝试 Windows 支持)粗略的实现可能是:
    path.qualify <- function(path) {
    path <- path.expand(path)
    if(!grepl("^/|([A-Z|a-z]:)", path)) path <- file.path(getwd(),path)
    path
    }

    但是,理想情况下,我希望可以跨平台处理 ../ 的相对路径。 , 符号链接(symbolic link)等。最好只使用 R 的解决方案(而不是 shell 脚本或类似的),但我找不到任何直接的方法来做到这一点,除非“从头开始”编码。

    有任何想法吗?

    最佳答案

    我想你想要 normalizePath() :

    > setwd("~/tmp/bar")
    > normalizePath("../tmp.R")
    [1] "/home/gavin/tmp/tmp.R"
    > normalizePath("~/tmp/tmp.R")
    [1] "/home/gavin/tmp/tmp.R"
    > normalizePath("./foo.R")
    [1] "/home/gavin/tmp/bar/foo.R"

    对于 Windows,有参数 winslash您可能希望一直设置它,因为它在 Windows 以外的任何东西上都会被忽略,因此不会影响其他操作系统:
    > normalizePath("./foo.R", winslash="\\")
    [1] "/home/gavin/tmp/bar/foo.R"

    (您需要转义 \ 因此 \\ )或
    > normalizePath("./foo.R", winslash="/")
    [1] "/home/gavin/tmp/bar/foo.R"

    取决于您希望如何呈现/使用路径。前者是默认设置( "\\" ),因此您可以在足够的情况下坚持使用它,而无需明确设置任何内容。

    在 R 2.13.0 上, "~/file.ext"位也有效(见评论):
    > normalizePath("~/foo.R")
    [1] "/home/gavin/foo.R"

    关于r - R中的完全限定文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5719523/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com