Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: create a new folder using the given path

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.

like image 977
Prradep Avatar asked Jun 17 '26 06:06

Prradep


1 Answers

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))
like image 120
drammock Avatar answered Jun 18 '26 22:06

drammock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!