[R] Formatting a path for unix with gsub

David Winsemius dwinsemius at comcast.net
Mon Dec 17 21:59:10 CET 2012


On Dec 17, 2012, at 9:44 AM, Nathan Skene wrote:

> 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?

You are probably being fooled by the print representation of backslashes in R output:

> gsub("\\s","\\\\ ",path)
[1] "/nfs/users/nfs_n/ns9/\\ Phenotype\\ Analysis/Results/Run_AmplRatio_neg\\ BinaryAll\\ trained\\ without\\ akapn+tnik.csv"

To check for the presence of backslashes with grepl, you need an R-grep pattern of "\\\\"

> grepl("\\\\", "\ ")   # surprise?  "\ " is not what it appears.
[1] FALSE
> grepl("\\\\", "\\ ")
[1] TRUE

> nchar("\ ")
[1] 1
> nchar("\\ ")
[1] 2


-- 
David Winsemius
Alameda, CA, USA




More information about the R-help mailing list