10

Possible Duplicate:
How do I extract a file/folder_name only from a path?

May I ask you how I can get the last subdirectory of a path. For example I want to get the subdirectory "7" and the following code fails:

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

Thank you in advance

Community
  • 1
  • 1
Apostolos Polymeros
  • 823
  • 1
  • 8
  • 19

2 Answers2

28

You could also use the built-in function basename:

basename(Path)
[1] "7"
James
  • 65,548
  • 14
  • 155
  • 193
  • 2
    Interesting that this currently has almost 2x the up-votes compared to the same answer in the previous question (7 vs 4)... – Joshua Ulrich Dec 18 '12 at 21:17
5

You have to add a second pair of \\ to escape the \ to the regex:

> Path <- "123\\456\\7"
> Split <- strsplit(Path, "\\\\")
> Split[[1]][length(Split[[1]])]
[1] "7"
thelatemail
  • 91,185
  • 12
  • 128
  • 188
melopsitaco
  • 176
  • 4