R: create a new folder using the given path
Asked Answered
F

1

8

I would like to create a new folder(newPack) in the parent folder(pathPos) of a given path(path) using R functions.

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)

I could achieve this using the above code, but I strongly feel there is a better option of doing it. If you know of any, please let me know.

Frostbite answered 19/12, 2018 at 16:41 Comment(5)
Maybe with ?basename.Hypocrisy
I assume you meant dirname(). Thanks, it avoids usage of stringi functions: stri_locate_last_fixed, stri_sub in the above snippet. i.e., pathNew <- paste(dirname(path), '/', newPack, sep = '')Frostbite
How about setwd(path); setwd(".."); dir.create(newPack);Communard
@Frostbite Oops! Right, dirname.Hypocrisy
@Communard Thanks, I could use that but it is more tedious to change the working directory thrice :(Frostbite
P
13
path <- "/foo/bar/baz"
newfolder <- "qux"
newpath <- file.path(dirname(path), newfolder)
print(newpath)
# "/foo/bar/qux"
dir.create(newpath)

Or, skipping the intermediate creation of newpath:

path <- "/foo/bar/baz"
newfolder <- "qux"
dir.create(file.path(dirname(path), newfolder))
Proserpina answered 20/12, 2018 at 18:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.