Several months ago I asked something similar, but I was using JavaScript to check if provided string is a “valid” R object name. Now I’d like to achieve the same by using nothing but R. I suppose that there’s a very nice way to do this, with some neat (not so) esoteric R function, so regular expressions seem to me as the last line of defence. Any ideas?
Oh, yeah, using back-ticks and stuff is considered cheating. =)
Edited 2013-1-9 to fix regular expression. Previous regular expression, lifted from page 456 of John Chambers’ "Software for Data Analysis", was (subtly) incomplete. (h.t. Hadley Wickham)
There are a couple of issues here. A simple regular expression can be used to identify all syntactically valid names — but some of those names (like
ifandwhile) are ‘reserved’, and cannot be assigned to.Identifying syntactically valid names:
?make.namesexplains that a syntactically valid name:Here is the corresponding regular expression:
Identifying unreserved syntactically valid names
To identify unreserved names, you can take advantage of the base function
make.names(), which constructs syntactically valid names from arbitrary character strings.Putting it all together
For more discussion of these issues, see the r-devel thread linked to by @Hadley in the comments below.