tmrgn
tmrgn

Reputation: 23

Using a loop to rename column names

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.

Upvotes: 1

Views: 1928

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 546193

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))

Upvotes: 2

Related Questions