0

I have many data frames that I need to use the first row of each as their column names.

So I write this line but it does not work:

colnames <- colnames(df) {
  colnames(df) <- df[1,]
  df <- df[-1, ] 
}

Do you have any idea what's wrong with it? Thanks!

Edo
  • 7,567
  • 2
  • 9
  • 19
Bing
  • 57
  • 4
  • Does this answer your question? [How to change the first row to be the header in R?](https://stackoverflow.com/questions/23209330/how-to-change-the-first-row-to-be-the-header-in-r) – Edo Oct 28 '20 at 14:56
  • 1
    Are you trying to define a function? I think you need `colnames <- function(df) {...` not `colnames <- colnames(df) {...`. You should also make the last line `df` or `return(df)`. And you may have issues because `df[1, ]` is a `data.frame`, not a character vector. Perhaps try `colnames(df) <- unlist(df[1, ])` – Gregor Thomas Oct 28 '20 at 14:56
  • 1
    You have not written function – user4933 Oct 28 '20 at 14:56
  • If possible, I'd also recommend fixing this problem when your read in the data, not after reading it incorrectly. Whatever you're using to import the data should have arguments to skip rows if needed and get the headers from wherever they show up. – Gregor Thomas Oct 28 '20 at 14:59

0 Answers0