1

I'm really new to coding and R in general. I'm working a df with 77 variable names. I'd like to rename most but not all of them. Here is the code I'm currently using:

colnames(df)[colnames(df) == 'oldName'] <- 'newName'

But it is really tedious to change one at a time. Is there a way to do it with one block of code?

Ryan
  • 71
  • 2
  • 7
  • 1
    Use `%in%` instead of `==`. If you are using `setnames` from `data.table`, it becomes easy as you can use the specific column to rename – akrun Oct 18 '17 at 01:59
  • 1
    and look at `?setNames` – SymbolixAU Oct 18 '17 at 01:59
  • Depends if the names are similar enough that an algorithm expressed as code can rename most/all of them. What are some examples of the names? – neilfws Oct 18 '17 at 02:23

1 Answers1

1

dplyr::rename is pretty handy for this, e.g.,

mtcars %>% dplyr::rename(
  `miles per gallon` = mpg,
  number_gears = gear
)
amanda
  • 321
  • 5
  • 12