[R] help with regexp mass substitution
Luca Braglia
braglia at poleis.eu
Fri Oct 2 11:39:56 CEST 2009
Hello *
i have to rename a lot of variables, and, given that they have regular name constructs, I would like to use regexps.
Here's a dump of my head(names(df))
varnames <- c("id.quest", "txt.1.3", "col1.1.3", "col2.1.3", "col3.1.3",
"col4.1.3", "col5.1.3", "txt.2.3", "col1.2.3", "col2.2.3", "col3.2.3",
"col4.2.3", "col5.2.3", "txt.3.3", "col1.3.3", "col2.3.3", "col3.3.3",
"col4.3.3", "col5.3.3", "txt.4.3", "col1.4.3", "col2.4.3", "col3.4.3",
"col4.4.3", "col5.4.3", "txt.5.3", "col1.5.3", "col2.5.3", "col3.5.3",
"col4.5.3", "col5.5.3", "txt.6.3", "col1.6.3", "col2.6.3", "col3.6.3",
"col4.6.3", "col5.6.3", "txt.7.3", "col1.7.3", "col2.7.3", "col3.7.3",
"col4.7.3", "col5.7.3", "txt.8.3", "col1.8.3", "col2.8.3", "col3.8.3",
"col4.8.3", "col5.8.3", "txt.9.3", "col1.9.3", "col2.9.3", "col3.9.3",
"col4.9.3", "col5.9.3", "txt.10.3", "col1.10.3", "col2.10.3",
"col3.10.3", "col4.10.3", "col5.10.3", "txt.11.3", "col1.11.3",
"col2.11.3", "col3.11.3", "col4.11.3", "col5.11.3", "txt.12.3",
"col1.12.3", "col2.12.3", "col3.12.3", "col4.12.3", "col5.12.3",
"txt.13.3", "col1.13.3", "col2.13.3", "col3.13.3", "col4.13.3",
"col5.13.3", "txt.14.3", "col1.14.3", "col2.14.3", "col3.14.3",
"col4.14.3", "col5.14.3", "txt.15.3", "col1.15.3", "col2.15.3",
"col3.15.3", "col4.15.3", "col5.15.3", "txt.16.3", "col1.16.3",
"col2.16.3", "col3.16.3", "col4.16.3", "col5.16.3", "txt.17.3",
"col1.17.3", "col2.17.3")
I'd like to convert only ^col variables to have eg
>From "col4.1.3" --> To "dom3.rig1.col4"
to test the matching regex I've tryied
grep("^col\\d{1,2}.\\d{1,2}.\\d{1,2}$",varnames, perl=T, value=T)
to substitute the ^col variables, I've tryied
gsub("^col(\\d{1,2}).(\\d{1,2}).(\\d{1,2})", "dom\\3.rig\\2.col\\1", varnames)
I'm a newbie with regexps and I got the starting vector (==varnames)
all(gsub("^col(\\d{1,2}).(\\d{1,2}).(\\d{1,2})", "dom\\3.rig\\2.col\\1", varnames) == varnames )
How can I do?
Many thanks and have a nice weekend.
Luca
More information about the R-help
mailing list