objects(pattern=...) and parsing of character strings

Brett Presnell (presnell@maths.anu.edu.au)
Mon, 19 Jan 1998 20:14:26 +1100


I took the following example directly from the help for objects():

> SP500 <- S.P500 <- 1
> objects(pattern = "^S\.")
[1] "S.P500" "SP500"

Of course in the help file this returns only "S.P500". The problem is
that grep() doesn't do what the code in objects() is expecting:

> what <- objects()
> what[grep("^S\.",what)]
[1] "S.P500" "SP500"

This in turn is caused because paste() is eating the "\" in "\.":

> paste("(","^S\.",")",sep="",collapse="|")
[1] "(^S.)"

Actually, I suppose the S parser is eating the "\" before it ever gets
to paste(). Something about this seems like a bug to me, but I'm not
always sure what I should expect from character operations in S. Note
that S eats the "\" in "\.","\*","\^","\$","\(","\)","\[", and "\]",
but not in "\\". Maybe if I just remember that at all times I'll be
right.

An easy fix to the original problem is

> objects(pattern="^S\\.")
[1] "S.P500"

On the other hand, it doesn't matter whether you escape
the "^" above or not:

> objects(pattern="\^S\\.")
[1] "S.P500"

and of course

> objects(pattern="\\^S\\.")
character(0)

But check this out:

> objects(pattern="^S\\.")
[1] "S.P500"
> objects(pattern="^S\\\.")
[1] "S.P500"
> objects(pattern="^S\\\\.")
[1] "S.P500"
> objects(pattern="^S\\\\\.")
[1] "S.P500"
> objects(pattern="^S\\\\\\.")
character(0)

This seems pretty strange to me. Actually, it seems very strange.
Deeper examination must explain it, but I don't think that the number
of "\"s doesn't get reduced by more than 1, and I don't think egrep
ignores that many "\"s in a row.

Is it just me? If so, can someone set me straight here.

Anyway, I suppose this can be considered a bug report, if not for
paste (+grep+objects), then at least for the help file for objects().

In case MathSoft is listening, I'm working with

S-PLUS : Copyright (c) 1988, 1996 MathSoft, Inc.
S : Copyright AT&T.
Version 3.4 Release 1 for Sun SPARC, SunOS 5.3 : 1996

though the machines I've tried this on were actually running SunOS
5.4--5.6.

Brett Presnell
presnell@maths.anu.edu.au