Use either > gsub(" ", "\\\\ ", "one two three") # double space after 'two' [1] "one\\ two\\ \\ three" or > gsub(" ", "\\ ", "one two three", fixed=TRUE) [1] "one\\ two\\ \\ three"
When 'fixed' is not TRUE then a backslash gives a special meaning to the next character in the replacement argument. E.g., "\\1" means to put the match corresponding to the first parenthesized subpattern into the replacement and, when perl=TRUE "\\U" means to capitalize the alphabetic characters in \\<digit> replacements. E.g., > gsub("([[:alpha:]])([[:alpha:]])", "\\2\\1", "one two three") [1] "noe wto htere" > gsub("( [[:alpha:]])", "\\U\\1", "one two three", perl=TRUE) [1] "one Two Three" Hence you need to have 2 backslashes in the replacement to put a backslash in the ouput when fixed is FALSE. You need to type 2 backslashes to put 1 backslash in a string, hence you need to type 4 backslashes to have 2 in the replacement string. Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf > Of Nathan Skene > Sent: Monday, December 17, 2012 9:45 AM > To: r-help@r-project.org > Subject: [R] Formatting a path for unix with gsub > > I have a path: > > path = "/nfs/users/nfs_n/ns9/ > Phenotype Analysis/Results/Run_AmplRatio_neg > BinaryAll trained without akapn+tnik.csv" > > I wish to replace the spaces with "\ " so that it can be read by a system > call to unix. > > Using gsub I try: > > > gsub(" ","\\ ",path) > [1] "/nfs/users/nfs_n/ns9/Phenotype Analysis/Results/Run_AmplRatio_neg > BinaryAll trained without akapn+tnik.csv" > > Various variations on this result in either adding no backslashes, or two at > once. How do I just get one backslash inserted? > > Thanks > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > 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. ______________________________________________ R-help@r-project.org mailing list 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.