I have a dataframe with 95 cols and you want to rename a lot of them with simple regular expressions, like the snippet at the bottom, there are ~ 30 such lines. Any other columns that do not match the search regular expression should be left untouched.
**** Example: names (tr) = c ('foo', 'bar', 'xxx_14', 'xxx_2001', 'yyy_76', 'baz', 'zzz_22', ...) ** **
I started with a wall of 25 gsub () s - raw but effective:
names(tr) <- gsub('_1$', '_R', names(tr))
names(tr) <- gsub('_14$', '_I', names(tr))
names(tr) <- gsub('_22$', '_P', names(tr))
names(tr) <- gsub('_50$', '_O', names(tr))
... yada yada
@Joshua: mapply does not work, it turns out to be more complex and impossible to vectorize. names (tr) contains other columns, and when these patterns occur, you cannot assume that they all occur, not to mention the exact order that we determined. Therefore, try 2:
pattern <- paste('_', c('1','14','22','50','52','57','76','1018','2001','3301','6005'), '$', sep='')
replace <- paste('_', c('R','I', 'P', 'O', 'C', 'D', 'M', 'L', 'S', 'K', 'G'), sep='')
do.call(gsub, list(pattern, replace, names(tr)))
Warning messages:
1: In function (pattern, replacement, x, ignore.case = FALSE, perl = FALSE, :
argument 'pattern' has length > 1 and only the first element will be used
2: In function (pattern, replacement, x, ignore.case = FALSE, perl = FALSE, :
argument 'replacement' has length > 1 and only the first element will be used
Can this fix it for me?
EDIT: I read everything around SO and R doc on this subject for more than one day and couldn’t find anything ... then when I post it, I think about searching for the “translation table [r]” and I find xlate, This is not mentioned elsewhere in the grep / sub / gsub documentation.
Is there anything in base/gsubfn/data.tableetc so that I can write one search and replace instruction? (e.g. dictionary or translation table)
Can you improve my clumsy syntax for calling on a tr link? (should not create a temporary copy of all df)
EDIT2: :
(xlate) , , , (, "_14 $" ).
gsub() strsplit() '_', xlate , () . 1/2- .
gsub() s.