R: extract directory from path

Possible duplicate:
How to extract file / folder_name from path only?

May I ask you how I can get the last subdirectory of the path. For example, I want to get the subdirectory "7", and the following code does not work:

Path <- "123\\456\\7"
Split <- strsplit(Path, "\\") # Fails because of 'Trailing backslash'
LastElement <- c[[1]][length(Split[[1]])]

Thank you in advance

+5
source share
2 answers

You can also use the built-in function basename:

basename(Path)
[1] "7"
+15
source

You must add a second pair \\to output \to the regular expression:

> Path <- "123\\456\\7"
> Split <- strsplit(Path, "\\\\")
> Split[[1]][length(Split[[1]])]
[1] "7"
+4
source

All Articles