Search code examples
rdataframeprefix

Add column name as prefix for specific columns


I have a data frame:

    df = read.table(text="race  Chr1    Chr08   Chr11   rep1    rep2    rep3    rep4    rep5
    race1   P54 P88 P54 151 142 267 127 161
    race1   P54 P88 P88 131 203 120 300 223
    race1   P54 P54 P88 165 271 73  170 241
    race1   P54 P54 P54 206 235 76  67  159", header=T, stringsAsFactors=F)

I would like to add the column name as prefix for columns 2:4, I tried "paste" in a loop or apply. either doesn't work.

for (i in 2:4){
  df[i] <- paste(names(df[i]),df[i],sep=".")}

or

df[2:4] <- apply(df[2:4],2, function(x) paste(colnames(x),x, sep="."))

The result is expected:

        result = read.table(text="race  Chr1    Chr08   Chr11   rep    rep2 rep3    rep4    rep5
race1   Chr1.P54    Chr08.P88   Chr11.P54   151 142 267 127 161
race1   Chr1.P54    Chr08.P88   Chr11.P88   131 203 120 300 223
race1   Chr1.P54    Chr08.P54   Chr11.P88   165 271 73  170 241
race1   Chr1.P54    Chr08.P54   Chr11.P54   206 235 76  67  159", header=T, stringsAsFactors=F)

Thanks for helps.


Solution

  • We can use col() to get a matrix of names for those columns, then paste it onto the columns after we have coerced them to a matrix.

    df[2:4] <- paste(col(df[2:4], TRUE), as.matrix(df[2:4]), sep=".")
    df
    #    race     Chr1     Chr08     Chr11 rep1 rep2 rep3 rep4 rep5
    # 1 race1 Chr1.P54 Chr08.P88 Chr11.P54  151  142  267  127  161
    # 2 race1 Chr1.P54 Chr08.P88 Chr11.P88  131  203  120  300  223
    # 3 race1 Chr1.P54 Chr08.P54 Chr11.P88  165  271   73  170  241
    # 4 race1 Chr1.P54 Chr08.P54 Chr11.P54  206  235   76   67  159
    

    You could also run rep(names(df[2:4]), each=nrow(df)) in place of col().