Create header of a dataframe from the first row in

2020-07-24 05:42发布

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?

标签: r indexing
2条回答
虎瘦雄心在
2楼-- · 2020-07-24 06:19

Try this:

> colnames(a) <- unlist(a[1,])
> a
  f g h
1 f g h
2 2 3 2
3 3 7 4
查看更多
劫难
3楼-- · 2020-07-24 06:38

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)
查看更多
登录 后发表回答