从完整路径中仅提取文件名之前的文件夹名称

Extract only folder name right before filename from full path

我有以下路径

filePath <- "/data/folder1/subfolder1/foo.dat"

我想获取 subfolder1,这是 foo.dat 所在的位置。我看到了其他语言的解决方案,但没有在 R 中找到解决方案。最简单的方法是什么?谢谢!

我试过的

> basename(filePath)
[1] "foo.dat"

> dirname(filePath)
[1] "/data/folder1/subfolder1"

这可能解决:

filePath <- "/data/folder1/subfolder1/foo.dat"

basename(dirname(filePath))

http://www.r-fiddle.org/#/fiddle?id=IPftVEDk&version=1

这可能不是最好的答案,但对你有用:

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