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

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Fri 10 Jun 2005 - 03:03:22 EST


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

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Received on Fri Jun 10 03:11:14 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:28 EST