1

I'm using rename from the dplyr library in R to rename column names. I tried to use a loop to achieve this, which runs without error. However, no column names are updated. The loop is:

for (i in 1:length(columns)) {
  newcol <- columns[i]
  oldcol <- names(census)[i]
  rename(census, newcol = oldcol) 
}

The 'columns' variable is a vector containing the new column names (of the same length as the old column names), and 'census' is the tibble containing the data with old column names. When just printing 'newcol' and 'oldcol' for each loop iteration, the names are correct - they just don't seem to then be renamed using the 'rename' line.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
tmrgn
  • 15
  • 6
  • 2
    dplyr's functions don't rewrite their output. If you want to rename columns, you need to assign the data frame back to itself. There's also no need for a loop; `rename` can take any number of names at once, and can rename based on positions as well – camille Jan 05 '22 at 16:14
  • Understood, thanks. – tmrgn Jan 05 '22 at 16:23
  • Some explanation here: https://stackoverflow.com/q/33335636/5325862 – camille Jan 05 '22 at 16:32

1 Answers1

2

Camille’s comment explains why your code doesn’t work.

To fix the code, you can drop the loop and directly assign the column names:

colnames(census) <- columns

When using rename, a bit more effort is required, since rename expects unevaluated column names, you need to tell it to evaluate the variables:

for (i in seq_along(columns)) {
  newcol <- columns[i]
  oldcol <- colnames(census)[i]
  census <- rename(census, !! newcol := !! oldcol) 
}

Or, once more dropping the unnecessary loop:

census <- rename(census, !!! setNames(colnames(census), columns))
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • That's great, thank you. The assignment requires the use of dplyr functions hence the use of `rename`. Thanks also for introducing me to `!!!` and `!!`! – tmrgn Jan 05 '22 at 16:35