Extract only folder name right before filename from full path

Viewed 6493

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"
2 Answers

This may not be the prettiest answer, but it will work for you:

unlist(strsplit(filePath, '/'))[length(unlist(strsplit(filePath, '/')))-1]
Related