# setNames vs. setnames in R (+ Examples) | stats & data.table Package

In this R tutorial, I’ll show you how to apply the **setNames function** of the R package stats and the **setnames function** of the R package data.table. The two functions are designed for slightly **different situations**, which sometimes leads to confusions. That’s why I’m explaining both functions in the same tutorial.

**Basic R Syntax of setNames [stats Package]:**

setNames(x, c("name1", "name2", "name3")) |

setNames(x, c("name1", "name2", "name3"))

setNames() sets the names of a data object and returns the object.

**Basic R Syntax of setnames [data.table Package]:**

setnames(data, "name_old", "name_new") |

setnames(data, "name_old", "name_new")

setnames() changes the names of a data.frame or data.table by reference.

In the following R programming tutorial, I’ll show **an example for each of the functions**.

Let’s start right away…

## Example 1: setNames R Function [stats Package]

In the first example, I’ll illustrate the usage of the setNames R Function of the stats package. Let’s first create an example vector:

x <- 1:5 # Create example vector x # Print example vector to RStudio console # 1 2 3 4 5 |

x <- 1:5 # Create example vector x # Print example vector to RStudio console # 1 2 3 4 5

Our example vector consists of the numbers 1 to 5. Now let’s assign a name to each of these numbers via setNames():

x_names <- setNames(x, letters[1:5]) # Apply setNames function x_names # Print updated vector to RStudio console # a b c d e # 1 2 3 4 5 |

x_names <- setNames(x, letters[1:5]) # Apply setNames function x_names # Print updated vector to RStudio console # a b c d e # 1 2 3 4 5

Easy! So what is the difference compared to the setnames function of the data.table package?

## Example 2: setnames R Function [data.table Package]

These are the main differences between setNames [stats Package] and setnames [data.table Package]:

- setnames of the data.table package has a lower case n instead of an upper case N.
- setnames can only be applied to data.table and data.frame objects.
- setnames changes names
**by reference**.

Let’s do an example…

First, we need to install and load the data.table package. Note that we did not have to do this in Example 1, since the stats package is automatically loaded with base R.

install.packages("data.table") # Install data.table package library("data.table") # Load data.table package |

install.packages("data.table") # Install data.table package library("data.table") # Load data.table package

Now, let’s create an example data.frame for the application of setnames:

data <- data.frame(x1 = 1:5, # Create example data.frame x2 = 6:10, x3 = 11:15) data # Print example data.frame to RStudio console |

data <- data.frame(x1 = 1:5, # Create example data.frame x2 = 6:10, x3 = 11:15) data # Print example data.frame to RStudio console

**Table 1: Example data.frame Before Application of setnames().**

Our example data consists of three columns with the column names x1, x2, and x3.

Now, we can use the setnames R function to rename certain column names:

setnames(data, # Apply setnames function c("x1", "x3"), c("x4", "x5")) data # Print updated example data.frame |

setnames(data, # Apply setnames function c("x1", "x3"), c("x4", "x5")) data # Print updated example data.frame

**Table 2: Example data.frame After Application of setnames().**

The colnames x1 and x3 were replaced by x4 and x5.

## Video: Related Functions

As you have seen, setNames and setnames can and should be applied in different data situations. However, there are many other functions that could also be used instead of setNames and setnames. In the following video, I’m showing you how to rename column names in R with the colnames function – one of the alternatives for setnames:

## Further Reading

### Subscribe to my free statistics newsletter:

### R Tutorials

abs Function in R

all & any R Functions

Set Aspect Ratio of Plot

attach & detach R Functions

attr, attributes & structure in R

cbind R Command

Change ggplot2 Legend Title

Character to Numeric in R

Check if Object is Defined

col & row sums, means & medians

Complete Cases in R

Concatenate Vector of Strings

Convert Date to Weekday

cumsum R Function

Data Frame Column to Numeric

diff Command in R

difftime R Function

dim Function in R

dir R Function

Disable Scientific Notation

Draw Segments in R

droplevels R Example

Evaluate an Expression

Extract Characters from String

Factor to Numeric in R

Format Decimal Places

get, get0 & mget in R

is.na R Function

is.null Function in R

jitter R Function

Join Data with dplyr Package

length Function in R

lowess R Smoothing Function

max and min Functions in R

NA Omit in R

nchar R Function

ncol Function in R

nrow Function in R

outer Function in R

pairs & ggpairs Plot

parse, deparse & R expression

paste & paste0 Functions in R

pmax and pmin R Functions

polygon Plots in R

pretty R Function

R Find Missing Values

R Functions List (+ Examples)

R NA – Values

R Replace NA with 0

rbind & rbind.fill in R

Read Excel Files in R

readLines, n.readLines & readline

Remove Element from List

Remove Legend in ggplot2

Rename Column Name in R

Replace Last Comma of String

rev R Command

Round Numeric Data in R

Save & Load RData Workspace

scan R Function

setdiff R Function

setNames vs. setnames in R

sink Command in R

Sort, Order & Rank Data in R

sprintf Function in R

Square Root in R

str_c Function of stringr Package

str_sub Function of stringr Package

strptime & strftime Functions

substr & substring R Commands

sweep R Function

Transform Data Frames

union Function in R

unlist in R

weekdays, months, quarters & julian in R

with & within R Functions

Write Excel File in R