简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM