2

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?

Sam
  • 7,252
  • 16
  • 46
  • 65
joaoal
  • 1,892
  • 4
  • 19
  • 29
  • not sure why.. but you can just wrap `a[1, ]` in `unlist()` – rawr Mar 28 '14 at 14:04
  • 2
    Why do you have this data.frame? Looks like a problem that should be solved during data import/creation. – Roland Mar 28 '14 at 14:06
  • @Roland I import a csv containing factors and numerical data. therefore I can't use a matrix...if this is what you mean. – joaoal Mar 28 '14 at 17:37
  • If you import a CSV, `read.csv` should recognize the column headers. – Roland Mar 28 '14 at 20:33
  • yes. but the first line does not contain the actual header but metadata-blabla. Bad secondary data I have to clean up. – joaoal Apr 03 '14 at 19:38

3 Answers3

2

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)
user3472874
  • 151
  • 5
1

Try this:

> colnames(a) <- unlist(a[1,])
> a
  f g h
1 f g h
2 2 3 2
3 3 7 4
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
1
janitor::row_to_names(a,1)

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

Lazarus Thurston
  • 1,197
  • 15
  • 33