I have the following path
filePath <- "/data/folder1/subfolder1/foo.dat"
I'd like to get subfolder1
which is where foo.dat
locates. I saw solutions in other languages but haven't found one in R. What is the simplest way to do it? Thank you!
What I tried
> basename(filePath)
[1] "foo.dat"
> dirname(filePath)
[1] "/data/folder1/subfolder1"
Paths include the root, the filename, or both. That is, paths can be formed by adding either the root, filename, or both, to a directory.
dirname() to get the directory folder (name) from a path string. If you want to get only the directory name directly above the file, use os. path. basename() .
Use os.remove() function to delete File The OS module in Python provides methods to interact with the Operating System in Python. The remove () method in this module is used to remove/delete a file path.
This may solve:
filePath <- "/data/folder1/subfolder1/foo.dat"
basename(dirname(filePath))
http://www.r-fiddle.org/#/fiddle?id=IPftVEDk&version=1
This may not be the prettiest answer, but it will work for you:
unlist(strsplit(filePath, '/'))[length(unlist(strsplit(filePath, '/')))-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With