2

My question is about renaming multiple column names at once.

I have a dataframe called 'growth' with 46 columns.

Columns 2:46 are all named as dates, but all of the dates have an X in front of them, e.g. 'X1981'.

Naturally I want to remove the X from all of the column names.

I cannot understand why the following is not working:

colnames(growth[ ,2:length(growth)]) <- substring(colnames(growth[ ,2:length(growth)]),2)

Please help me with some insights.

Wade Byron Profe
  • 155
  • 2
  • 3
  • 19
  • 1
    Probably related to [this](https://stackoverflow.com/questions/23427925/difference-between-namesdf1-and-namesdf1) – David Arenburg Jun 24 '18 at 11:49
  • You actually should reshape your wide data to long format, having a *Year* column and values in adjacent column. This scales better and computation is much easier. – Parfait Jun 24 '18 at 13:03
  • Possible duplicate of [Difference between \`names(df\[1\]) <- \` and \`names(df)\[1\] <- \`](https://stackoverflow.com/questions/23427925/difference-between-namesdf1-and-namesdf1) – Rui Barradas Jun 24 '18 at 14:12

1 Answers1

2

Nevermind, I changed the instruction to...

names(growth)[2:46] <- substring(names(growth)[2:46],2)

...and now it works. Clearly it had something to do with how I was subsetting the columns.

Wade Byron Profe
  • 155
  • 2
  • 3
  • 19
  • 1
    Good job. Note that if growth has 46 columns then you can replace `2:46` by more concise `-1`. – s_baldur Jun 24 '18 at 12:15
  • That is probably because doing `colnames(growth[, 2:46]) <- ...` you create a subset of your original `data.frame`, than you create a character vector with your `substring()` call, and after that you assign this character vector to the earlier created subset of `growth`. So the output is a character vector of (desired) names. If you enclose your code into parenthesis you will see something like: `[1] "2" "3" "4"..."45" "46"`. However, I believe someone with better knowledge of R would explain it better than me, or would correct me if I got it wrong. – utubun Jun 24 '18 at 12:15