rename()

The function rename() does what it sounds like: it changes the name of a specified column. The syntax is to pick a new column name and set it equal to the old column name. With the following code, we can change the column body_mass_g to be called weight:

If we want to rename two columns, we can do both inside the same function, just separated by a comma:

That code will rename two columns. Notice that after the comma we went to the next line. Doing so makes it easier to read the code. R understands that a comma means that the code continues on the next line. Using a comma is different than using a pipe because the comma is only for if you are inside a single function and pipe is for stringing together multiple functions.

Notice that if I print penguins to the screen, it does not have the changed column names. Again, remember that if you want to make a change permanent, you need to assign it to a variable. If you want to permanently rename a column you can overwrite a variable by assigning it to the same original name. The following code would permanently change the two columns inside penguins.

penguins <- penguins |> 
  rename(weight = body_mass_g, 
         flipper = flipper_length_mm)

Be careful when overwriting variables. It is often not a good idea to overwrite your original dataset because you may want to have a record of things before any changes. Because of this I will often first read my data in as something like data_raw, so that then I can change it to just data but still have a record of the original.

When renaming columns, you should keep in mind R’s rules for variable names: no spaces and don’t start the variable with a numeric. So three islands or 3_islands would not be good variable names; rather use three_islands.