【问题标题】:R: create a new folder using the given pathR:使用给定路径创建一个新文件夹
【发布时间】:2018-12-19 16:41:56
【问题描述】:

我想使用 R 函数在给定路径 (path) 的父文件夹 (pathPos) 中创建一个新文件夹 (newPack)。

path <- "/m/home/user/unix/R/3.5/stringi"
newPack <- "stringr"

pathPos <- stringi::stri_locate_last_fixed(path, '/')[-1]
pathNew <- paste(stringi::stri_sub(path, 1, pathPos), newPack, sep = '')

dir.create(pathNew)

我可以使用上面的代码实现这一点,但我强烈认为有更好的选择。如果你知道的话,请告诉我。

【问题讨论】:

  • 也许是?basename
  • 我猜你的意思是dirname()。谢谢,它避免使用stringi 函数:stri_locate_last_fixedstri_sub 在上面的 sn-p 中。即pathNew &lt;- paste(dirname(path), '/', newPack, sep = '')
  • setwd(path); setwd(".."); dir.create(newPack);怎么样
  • @Prradep 哎呀!对,dirname
  • @Mako212 谢谢,我可以使用它,但是三次更改工作目录会更乏味:(

标签: r directory stringi


【解决方案1】:
path <- "/foo/bar/baz"
newfolder <- "qux"
newpath <- file.path(dirname(path), newfolder)
print(newpath)
# "/foo/bar/qux"
dir.create(newpath)

或者,跳过newpath的中间创建:

path <- "/foo/bar/baz"
newfolder <- "qux"
dir.create(file.path(dirname(path), newfolder))

【讨论】:

    猜你喜欢
    • 2017-08-06
    • 1970-01-01
    • 2011-05-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2021-10-10
    相关资源
    最近更新 更多