appending or Pasting names to Column names in R

Dinesh picture Dinesh · Nov 6, 2011 · Viewed 7.2k times · Source

I Have a tab delim file with 400 columns.Now I want to append text to the column names.ie if there is column name is A and B,I want it to change A to A.ovca and B to B.ctrls.Like wise I want to add the texts(ovca and ctrls) to 400 coulmns.Some column names with ovca and some with ctrls.All the columns are unique and contains more than 1000 rows.A sample code of the delim file is given below:

         X             Y         Z               A       B               C  
        2.34          .89       1.4             .92     9.40            .82
        6.45          .04       2.55            .14     1.55            .04
        1.09          .91       4.19            .16     3.19            .56
        5.87          .70       3.47            .80     2.47            .90

And i want the file to be look like:

       X.ovca     Y.ctrls      Z.ctrls       A.ovca     B.ctlrs       C.ovca  
        2.34          .89       1.4             .92     9.40            .82
        6.45          .04       2.55            .14     1.55            .04
        1.09          .91       4.19            .16     3.19            .56
        5.87          .70       3.47            .80     2.47            .90

Please do help me

Regards Thileepan

Answer

Ari B. Friedman picture Ari B. Friedman · Nov 6, 2011

If you data.frame is called dat, you can access (and write to) the column names with colnames(dat).

Therefore:

cn <- colnames(dat)
cn <- sub("([AXC])","\\1.ovca",cn)
cn <- sub("([YZB])","\\1.ctrls",cn)
colnames(dat) <- cn

> cn
[1] "X.ovca"  "Y.ctrls" "Z.ctrls" "A.ovca"  "B.ctrls" "C.ovca" 

The \\1 is called back-substitution within your regular expression. It will replace \\1 with whatever's inside the parentheses in the pattern. Since inside the parentheses you have a bracket, it will match any of the letters inside. In this case, "A" becomes "A.ovca" and "X" becomes "X.ovca".

If your variable names are more than one letter, easy enough to extend; just look up a bit on regex's.