Often data you’re working with has abstract column names, such as (x1, x2, x3…). Typically, the first step I take when renaming columns with r is opening my web browser.

The dataset cars is data from the 1920s on “Speed and Stopping Distances of Cars”. There is only 2 columns shown below.

```
colnames(datasets::cars)
[1] "speed" "dist"
```

If we wanted to rename the column “dist” to make it easier to know what the data is/means we can do so in a few different ways.

## Using dplyr:

```
cars %>%
rename("Stopping Distance (ft)" = dist) %>%
colnames()
[1] "speed" "Stopping Distance (ft)"
```

```
cars %>%
rename("Stopping Distance (ft)" = dist, "Speed (mph)" = speed) %>%
colnames()
[1] "Speed (mph)" "Stopping Distance (ft)"
```

## Using Base r:

```
colnames(cars)[2] <-"Stopping Distance (ft)"
[1] "speed" "Stopping Distance (ft)"
colnames(cars)[1:2] <-c("Speed (mph)","Stopping Distance (ft)")
[1] "Speed (mph)" "Stopping Distance (ft)"
```

## Using GREP:

```
colnames(cars)[grep("dist", colnames(cars))] <-"Stopping Distance (ft)"
"speed" "Stopping Distance (ft)"
```

I do recommend data.table::setnames()

Or after converting cars to data.table with `setDT(cars)`, you can do `setnames(cars, c(“dist”, “speed”), c(“Stopping Distance (ft)”, “Speed (mph)”))`. Immediate and without unnecessary copy in memory.

I guess there is a little typo in the result of first example of dplyr, and it should be:

“`

[1] “speed” “Stopping Distance (ft)”

“`

Thank you!

magrittr::set_colnames()

[…] To change the column names in the data frame you can go here to see a couple of different ways to rename columns in r. […]