[R] gsub: replacing slashes in a string

jim holtman jholtman at gmail.com
Wed Sep 14 19:06:10 CEST 2016


try this:

> gsub("\\\\", "/", test)
[1] "8/24/2016" "8/24/2016" "6/16/2016" "6/16/2016"




Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.

On Wed, Sep 14, 2016 at 12:25 PM, Joe Ceradini <joeceradini at gmail.com>
wrote:

> Hi all,
>
> There are many R help posts out there dealing with slashes in gsub. I
> understand slashes are "escape characters" and thus need to be treated
> differently, and display differently in R. However, I'm still stuck on
> find-replace problem, and would appreciate any tips. Thanks!
>
> GOAL: replace all "\\" with "/", so when export file to csv all slashes are
> the same.
>
> (test <- c("8/24/2016", "8/24/2016", "6/16/2016", "6\\16\\2016"))
>
> Lengths are all the same, I think (?) because of how R displays/deals with
> slashes. However, when I export this to a csv, e.g., there are still double
> slashes, which is a problem for me.
> nchar(test)
>
> Change direction of slashes - works.
> (test2 <- gsub("\\", "//", test, fixed = TRUE))
>
> Now lengths are now not the same....
> nchar(test2)
>
> Change from double to single - does not work. Is this because it actually
> is a single slash but R is just displaying it as double? Regardless, when I
> export from R the double slashes do appear.
> gsub("////", "//", test2, fixed = TRUE)
> gsub("////", "//", test2)
> gsub("////////", "////", test2, fixed = TRUE)
> gsub("////////", "////", test2)
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/
> posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list