rename(data, new_colname)Rename columns in a table
You want to rename one or more columns in a data frame.
Step 1 - Pass your data frame to dplyr::rename(). rename() will return a modified copy of this data frame.
Step 2 - Choose a new name for the column you wish to rename. Write the new name as an argument name in rename().
Step 3 - Set the new name equal to the current name.
rename(data, new_colname = old_colname)Example
weather_ contains hourly climate data collected near Monash University in Australia.
weather_# A tibble: 24 × 3
timestamp temperature wind_speed
<dttm> <dbl> <dbl>
1 2015-01-01 00:00:00 19.6 4.29
2 2015-01-01 01:00:00 20.5 3.56
3 2015-01-01 02:00:00 20.5 1.86
4 2015-01-01 03:00:00 21.4 1.21
5 2015-01-01 04:00:00 21.8 1.11
6 2015-01-01 05:00:00 22.4 1.9
7 2015-01-01 06:00:00 22.7 2.52
8 2015-01-01 07:00:00 22.7 3.36
9 2015-01-01 08:00:00 22.4 4.13
10 2015-01-01 09:00:00 22.6 4.25
# ℹ 14 more rows
The temperature column contains the temperature in degrees Celsius. We are concerned that someone else looking at this data may confuse this with temperature in Fahrenheit. Therefore, we want to rename the column to temp_cel.
To begin, we first load the dplyr package which contains rename(). We then pass weather_ to rename() and set our new column name, temp_cel, equal to our current column name, temperature.
library(dplyr)
weather_ %>%
rename(temp_cel = temperature)# A tibble: 24 × 3
timestamp temp_cel wind_speed
<dttm> <dbl> <dbl>
1 2015-01-01 00:00:00 19.6 4.29
2 2015-01-01 01:00:00 20.5 3.56
3 2015-01-01 02:00:00 20.5 1.86
4 2015-01-01 03:00:00 21.4 1.21
5 2015-01-01 04:00:00 21.8 1.11
6 2015-01-01 05:00:00 22.4 1.9
7 2015-01-01 06:00:00 22.7 2.52
8 2015-01-01 07:00:00 22.7 3.36
9 2015-01-01 08:00:00 22.4 4.13
10 2015-01-01 09:00:00 22.6 4.25
# ℹ 14 more rows
We see now the column is named temp_cel and the original column order is preserved.
Lastly, we save the dataset modified by rename() to a new object so it can be used later. As we do, we decide to rename the wind_speed column as well.
weather_rename <-
weather_ %>%
rename(temp_cel = temperature, ws = wind_speed)Rename more than one column
You can rename more than one column at a time by adding more arguments inside ofrename().
data %>%
rename(
new_colname1 = old_colname1,
new_colname2 = old_colname2
)rename() is the equivalent of SAS’s RENAME option used with the DATA or PROC step:
In SAS:
DATA data_rename;
SET data (RENAME = (old_colname = new_colname));or
PROC PRINT data (RENAME = (old_colname = new_colname));In R:
data_rename <-
data %>%
rename(new_colname = old_colname)