How to name the unnamed first column of a data.frame

dataframe, r

Solution

You could join the row names to the dataframe, like this:

mydf <- cbind(rownames(mydf), mydf)
rownames(mydf) <- NULL
colnames(mydf) <- c("COL1","VAL1","VAL2")

Or, in one step:

setNames(cbind(rownames(mydf), mydf, row.names = NULL), 
         c("COL1", "VAL1", "VAL2"))
#         COL1     VAL1        VAL2
# 1 hsa-let-7a 2.139890 -0.03477569
# 2 hsa-let-7b 2.102590  0.04108795
# 3 hsa-let-7c 2.061705  0.02375882
# 4 hsa-let-7d 1.938950 -0.04364545
# 5 hsa-let-7e 1.889000 -0.10575235
# 6 hsa-let-7f 2.264296  0.08465690

Problem

I have a data frame that looks like this: ``` > mydf val1 val2 hsa-let-7a 2.139890 -0.03477569 hsa-let-7b 2.102590 0.04108795 hsa-let-7c 2.061705 0.02375882 hsa-let-7d 1.938950 -0.04364545 hsa-let-7e 1.889000 -0.10575235 hsa-let-7f 2.264296 0.08465690 ``` Note that from 3 columns only 2nd and 3rd are names. What I want to do is to name the first column (plus rename the 2nd and 3rd). But why this command failed? ``` colnames(mydf) <- c("COL1","VAL1","VAL2"); ``` What's the right way to do it? It gave me: ``` Error in `colnames<-`(`*tmp*`, value = c("COL1", "VAL1", "VAL2" : 'names' attribute [3] must be the same length as the vector [2] ```

Original source