joaoal
joaoal

Reputation: 1982

Create header of a dataframe from the first row in the data frame

Suppose I have a dataframe:

a <- data.frame(a=c("f", 2, 3), b=c("g", 3, 7), c=c("h", 2, 4))

and I would like to create column names from the first row. MY guess was:

names(a) <- a[1,]

which gives:

names(a)
[1] "3" "3" "3"

I did not fully get what is happening. Can anyone explain and help me on how to do it the right way?

Upvotes: 2

Views: 6163

Answers (3)

Lazarus Thurston
Lazarus Thurston

Reputation: 1287

janitor::row_to_names(a,1)

janitor package gives the cleanest way to shift any data row up as column names.

Upvotes: 1

Jilber Urbina
Jilber Urbina

Reputation: 61154

Try this:

> colnames(a) <- unlist(a[1,])
> a
  f g h
1 f g h
2 2 3 2
3 3 7 4

Upvotes: 1

user3472874
user3472874

Reputation: 151

The columns of a are factors with each column having different levels. R casts them to ints. Since, for each column the letter appears last alphanumerically it gets assigned the value 3.

Try

names(a) = as.character(unlist(a[1,]))
names(a)

Upvotes: 2

Related Questions