user1234440
user1234440

Reputation: 23597

How to extract specific characters in R String

I have a file name string:

directoryLocation<-"\Users\me\Dropbox\Work\"

How can I extract all the "\" and replace it with "\"? In other languages, you can loop through the string and then replace character by character, but I don't think you can do that in R.

I tried

substr(directoryLocation,1,1)

but it is highly optimized to this case...how can it be more general?

Thanks

Upvotes: 0

Views: 975

Answers (3)

James
James

Reputation: 66874

gsub is the general tool for this, but as others have noted you need a confusing four slashes to account for the escapes: you need to escape for both R text and the regexp engine simultaneously.

An alternative, if using Windows, is to use normalizePath and setting the winslash parameter:

normalizePath(directoryLocation,winslash="/",mustWork=FALSE)
[1] "C:/Users/me/Dropbox/Work/"

Though this may perform additional work on expanding relative paths to absolute ones (seen here by prepending with C:).

Upvotes: 1

Thomas
Thomas

Reputation: 44565

At least on windows one needs to escape all of the backslashes, but gsub is what you want.

gsub("\\\\","/","\\Users\\me\\Dropbox\\Work\\")
[1] "/Users/me/Dropbox/Work/"

Upvotes: 0

Jake Burkhead
Jake Burkhead

Reputation: 6545

In theory this would do what you want

 gsub("\\\", "/", directoryLocation)

however...

R> directoryLocation<-"\\Users\\me\\Dropbox\\Work\\"
R> directoryLocation
[1] "\\Users\\me\\Dropbox\\Work\\"
R> gsub("\\\\", "/", directoryLocation)
[1] "/Users/me/Dropbox/Work/"

Upvotes: 0

Related Questions