Niek de Klein
Niek de Klein

Reputation: 8824

colnames(df[1,]) puts numbers instead of row 1 as colname

I have a dataframe df. When I print the first row I get

> print(df[1,])
V2         V3         V4         V5        
A          B          C          D

I want A,B, etc to be the colnames so I do

colnames(df) <- df[1,]

However, when I print the colnames I now get

> print(colnames(df))
[1] "1101" "852"  "782"  "534" 

        V2          V3         V4        
        A           B          C  
col1    48.6        2          0.2           
col2    68.7        3.4        0.3               
col3    34.2        2.7        0.5        

How should I set the colnames?

Upvotes: 1

Views: 193

Answers (1)

SuaveIncompetence
SuaveIncompetence

Reputation: 513

As Gregor and nicola have picked up your columns appear to be factors and colnames() needs a vector input not a dataframe, try the following:

colnames(df) <- as.vector(t(df[1,]))

t() transposes the vector to a single column matrix, as.vector() then drops the second dimension.

Example:

df <- data.frame(x1 = factor("a"),x2 = factor("b"),x3 = factor("c"),x4 = factor("d"))
colnames(df) <- as.vector(t(df[1,]))
df <- df[-1,] # removes the first row

Upvotes: 1

Related Questions