[R] dir() and RegEx and gsub()

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Jun 9 19:03:22 CEST 2005


On Thu, 9 Jun 2005, Hans-Peter wrote:

> Dear R-Users,
>
> I have two questions:
>
> a)
> in a directory there are 3 files:
> [1] "Data.~csv"            "Kopie von Data.~csv"  "VorlageTradefile.csv"
>
> The command "dir( fold, pattern = "\.csv" )" gives back *all* the 3 files
> With dir( fold, pattern = "\\.csv" ) I get back only VorlageTradefile.csv.
> I don't understand this behaviour, IMHO the regex expression "\.csv"
> becomes the string ".csv" and "\\.csv" becomes "\.csv". So the first
> string should catch it.

Catch what?  What do you actually want (you have not told us).

> This is also consistent with the result when I tried with the TRegExpr
> Tool. Could somebody explain what's going on here?

See the FAQ Q7.8: you need to double the backslashes.
This is _also_ mentioned in ?regexp.

I think you probably really intended dir( fold, pattern = "\\.csv$" )

> cat("\\.csv$", "\n")
\.csv$

may help illuminate the misconception.

> b)
> I need to handle a copied windows file path. This is certainly often
> asked but I didn't find a solution.

It is so often asked it really is a FAQ.

> How can I convert, e.g.
>
> myfile <- "D:\UebungenNDK\DataMining\DataMiningSeries.r"

I am sure that's not what you intended.  It has to be written as

myfile <- "D:\\UebungenNDK\\DataMining\\DataMiningSeries.r"

> in either:
>
> myfile
> [1]  "D:\\UebungenNDK\\DataMining\\DataMiningSeries.r"
>
> or:
> myfile
> [1]  "D:/UebungenNDK/DataMining/DataMiningSeries.r"
>
> Would be great to hear about a possibility!

It's all over the R code.  E.g.

gsub("\\", "/", myfile, fixed = TRUE)

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list