Row and column names in R

Data Manipulation in R Data transformation
Row and column names in R

The rownames and colnames functions allow you to get and set row and column names for matrix-like objects, such as data frames or matrices. The dimnames is similar, as it allows you to retrieve or set both the column and row names of an object.

Quick answer

Use rownames(df) and colnames(df) to get the names, and assign a vector with one name per row or column to set them. To rename only one column, select it by its current name.

df <- data.frame(x = 1:3, y = c("a", "b", "c"))

# Set all column names and row names
colnames(df) <- c("id", "letter")
rownames(df) <- c("r1", "r2", "r3")

# Rename a single column by name
colnames(df)[colnames(df) == "letter"] <- "char"

df
   id char
r1  1    a
r2  2    b
r3  3    c

Get and set row names with rownames

The rownames function allows you to retrieve the row names of a data frame or matrix. The syntax of the function is the following:

# Get row names
rownames(x)

# Set row names to "value" (usually a vector or NULL)
rownames(x) <- value

In the following block of code we create a sample data frame with two columns and ten rows. The data frame looks like this:

df <- data.frame(col1 = 1:10, col2 = 11:20)
df
   col1 col2
1     1   11
2     2   12
3     3   13
4     4   14
5     5   15
6     6   16
7     7   17
8     8   18
9     9   19
10   10   20

You can check the default row names with the rownames function. As the row names haven’t been set yet, the default names are the index of each row.

rownames(df)
"1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

Nonetheless, the rownames function can also be used to set the row names. For that purpose, you will need to assign the row names a vector with as many elements as rows.

rownames(df) <- paste("Row", 1:10)
rownames(df)
"Row 1"  "Row 2"  "Row 3"  "Row 4"  "Row 5"  "Row 6"  "Row 7"  "Row 8"  "Row 9"  "Row 10"

Now, if you check the sample data set you will see that the rows have the name you set with the previous code.

df
       col1 col2
Row 1     1   11
Row 2     2   12
Row 3     3   13
Row 4     4   14
Row 5     5   15
Row 6     6   16
Row 7     7   17
Row 8     8   18
Row 9     9   19
Row 10   10   20

Row names of a data frame must be unique and can’t contain missing values. Check the common errors section if you get an error when setting them.

Get and set column names with colnames

The colnames function behaves the same as rownames but for column names. The syntax is as follows:

# Get column names
colnames(x)

# Set column names to "value" (usually a vector or NULL)
colnames(x) <- value

If you want to check the column names of your object you just need to input the name of your object to the function.

colnames(df)
"col1" "col2"

You can also customize the column names of your object by assigning new values to the column names.

colnames(df) <- c("Column 1", "Column 2")
colnames(df)
"Column 1" "Column 2"

Now you can check that your data frame has the new column names:

df
       Column 1 Column 2
Row 1         1       11
Row 2         2       12
Row 3         3       13
Row 4         4       14
Row 5         5       15
Row 6         6       16
Row 7         7       17
Row 8         8       18
Row 9         9       19
Row 10       10       20

Rename a single column

You don’t need to pass all the names to rename only one column. Subset the vector of names and assign the new name to that element. The safest way is to select the column by its current name, because it still works if the order of the columns changes:

df <- data.frame(id = 1:3, letter = c("a", "b", "c"))

# Rename the column 'letter' to 'char'
colnames(df)[colnames(df) == "letter"] <- "char"
df
  id char
1  1    a
2  2    b
3  3    c

You can also select the column by its position. The following code renames the second column:

colnames(df)[2] <- "chr"
df
  id chr
1  1   a
2  2   b
3  3   c

The same approach works for row names, for example rownames(df)[rownames(df) == "old"] <- "new". If you work with dplyr, you can also rename columns with the rename function, with the syntax rename(df, new_name = old_name).

The dimnames function

The dimnames function can be used to retrieve both row and column names of an object. The output is a list where the first element are the row names and the second the column names.

dimnames(df)
[[1]]
 [1] "Row 1"  "Row 2"  "Row 3"  "Row 4"  "Row 5"  "Row 6"  "Row 7"  "Row 8"  "Row 9"  "Row 10"

[[2]]
[1] "Column 1" "Column 2"

You can access each of them by accessing each element of the list as in the example below.

# Row names
dimnames(df)[[1]]

# Column names
dimnames(df)[[2]]
"Row 1"  "Row 2"  "Row 3"  "Row 4"  "Row 5"  "Row 6"  "Row 7"  "Row 8"  "Row 9"  "Row 10"

"Column 1" "Column 2"

If you want to change the row and column names you can assign a new value with dimnames(x)[[1]] <- value or dimnames(x)[[2]] <- value, but it is recommended to use the rownames and colnames functions instead.

Remove column and row names

Sometimes you just want to remove the column and/or row names of your matrix or data frame. For that purpose you will need to assign the columns and/or rows to NULL.

# Remove row names
rownames(df) <- NULL

# Remove column names
colnames(df) <- NULL

# Check data frame
df

Now the data frame doesn’t have row or column names.

1   1 11
2   2 12
3   3 13
4   4 14
5   5 15
6   6 16
7   7 17
8   8 18
9   9 19
10 10 20

Note that in a data frame rownames(df) <- NULL doesn’t leave the rows without names, it resets them to the default index (1, 2, 3, …).

Convert a column to row names

A common task is to use the values of a column, such as an ID or a name, as the row names of a data frame. Consider the following data:

df <- data.frame(name = c("Ana", "Bob", "Carl"),
                 age = c(28, 35, 41),
                 height = c(165, 180, 175))
df
  name age height
1  Ana  28    165
2  Bob  35    180
3 Carl  41    175

In base R, assign the column to the row names and then remove the column setting it to NULL:

rownames(df) <- df$name
df$name <- NULL
df
     age height
Ana   28    165
Bob   35    180
Carl  41    175

If you are creating the data frame or reading a file, you can also use the row.names argument of data.frame or read.csv with the name or the position of the column, for example data.frame(df, row.names = "name") or read.csv("file.csv", row.names = 1).

The tibble package provides the column_to_rownames function, which does the same in a single step:

# install.packages("tibble")
library(tibble)

df <- data.frame(name = c("Ana", "Bob", "Carl"),
                 age = c(28, 35, 41),
                 height = c(165, 180, 175))

column_to_rownames(df, var = "name")
     age height
Ana   28    165
Bob   35    180
Carl  41    175

Remember that the values of the column must be unique and can’t be NA, as row names don’t allow duplicates.

Convert row names to a column

The opposite operation is very common with data sets that store information in the row names, such as mtcars, where the car models are the row names. In base R, create a new column with the row names and then reset the row names:

cars <- head(mtcars[, 1:3], 3)

cars <- cbind(model = rownames(cars), cars)
rownames(cars) <- NULL
cars
          model  mpg cyl disp
1     Mazda RX4 21.0   6  160
2 Mazda RX4 Wag 21.0   6  160
3    Datsun 710 22.8   4  108

We used cbind to place the new column in the first position. With cars$model <- rownames(cars) the column would be added at the end.

With tibble, the rownames_to_column function adds the row names as the first column and removes them in one step:

library(tibble)

cars <- head(mtcars[, 1:3], 3)
rownames_to_column(cars, var = "model")
          model  mpg cyl disp
1     Mazda RX4 21.0   6  160
2 Mazda RX4 Wag 21.0   6  160
3    Datsun 710 22.8   4  108

Row names and tibbles

Tibbles (the data frames used by the tidyverse) don’t support row names. If you convert a data frame with row names to a tibble, the row names are dropped without any warning:

library(tibble)

as_tibble(head(mtcars[, 1:3], 3))
# A tibble: 3 × 3
    mpg   cyl  disp
  <dbl> <dbl> <dbl>
1  21       6   160
2  21       6   160
3  22.8     4   108

To keep them, convert the row names to a column before or use the rownames argument of as_tibble:

as_tibble(head(mtcars[, 1:3], 3), rownames = "model")
# A tibble: 3 × 4
  model           mpg   cyl  disp
  <chr>         <dbl> <dbl> <dbl>
1 Mazda RX4      21       6   160
2 Mazda RX4 Wag  21       6   160
3 Datsun 710     22.8     4   108

As the tidyverse is designed around tibbles, if the row names contain information, store it in a column. If you try to set row names on a tibble you will get the warning Setting row names on a tibble is deprecated.

names vs colnames and row.names vs rownames

In data frames, names and colnames return the same, as a data frame is a list of columns:

df <- data.frame(x = 1:3, y = c("a", "b", "c"))

names(df)
colnames(df)
[1] "x" "y"
[1] "x" "y"

However, they are different for matrices. names returns the names of the individual elements (usually NULL), while colnames returns the column names:

m <- matrix(1:6, nrow = 2, dimnames = list(c("a", "b"), c("A", "B", "C")))

names(m)
colnames(m)
NULL
[1] "A" "B" "C"

Regarding rows, row.names is the function specific for data frames, while rownames works for data frames and matrices. For a data frame both return the same, so you can use either of them. The table below summarizes the differences:

Function Data frames Matrices Vectors and lists
colnames Column names Column names NULL
names Column names Names of elements Names of elements
rownames Row names Row names NULL
row.names Row names Row names NULL

As a rule of thumb, use colnames and rownames for matrices and data frames and names for vectors and lists.

Create valid and unique names

Column names with spaces or special characters, such as "Column 1", are allowed but they are inconvenient, because you need to write them between backticks (df$`Column 1`). The make.names function converts any string into a valid R name, replacing invalid characters with dots and adding an X at the beginning if the name starts with a number:

make.names(c("Column 1", "2nd col", "price ($)", "ok"))
[1] "Column.1"  "X2nd.col"  "price...." "ok"

To clean all the column names of a data frame use colnames(df) <- make.names(colnames(df)). This is what data.frame and read.csv do by default with check.names = TRUE.

If you have duplicated names, make.unique appends a sequence number to the repeated values, keeping the first one unchanged. This is very useful to create row names from a column with duplicates:

make.unique(c("a", "a", "b", "a"))
[1] "a"   "a.1" "b"   "a.2"

You can also get both results at once with make.names(x, unique = TRUE).

Common errors

Error: duplicate ‘row.names’ are not allowed

The row names of a data frame must be unique. If you assign a vector with repeated values you will get this error:

df <- data.frame(name = c("A", "A", "B"), v = 1:3)

rownames(df) <- df$name
Error in `.rowNamesDF<-`(x, value = value) :
  duplicate 'row.names' are not allowed
In addition: Warning message:
non-unique value when setting 'row.names': 'A'

The warning tells you which values are repeated. Fix the duplicates in your data, keep the values in a regular column instead of using them as row names or make them unique with make.unique:

rownames(df) <- make.unique(df$name)
df
    name v
A      A 1
A.1    A 2
B      B 3

You will get the same error with read.csv(..., row.names = 1) if the first column has repeated values, the similar error duplicate row.names: A with data.frame(..., row.names = "name"), and missing values in 'row.names' are not allowed if the vector contains NA.

Error: ‘names’ attribute [n] must be the same length as the vector [m]

This error appears when you assign more column names than columns. In the following example the data frame has two columns but we pass three names:

df <- data.frame(x = 1:3, y = 4:6)

colnames(df) <- c("a", "b", "c")
Error in names(x) <- value :
  'names' attribute [3] must be the same length as the vector [2]

The number between brackets after 'names' attribute is the number of names you passed, and the second one is the number of columns. Check ncol(df) and pass the same number of names, or rename only the columns you need as shown in the rename section.

Be careful, as passing fewer names doesn’t raise any error in a data frame: the rest of the columns are named NA. For row names, a vector of the wrong length returns invalid 'row.names' length, and in a matrix you will get length of 'dimnames' [2] not equal to array extent.

Error: invalid ‘dimnames’ given for data frame

This error appears when you use dimnames to set the names of a data frame and the list doesn’t have exactly two elements with one name per row and one per column:

df <- data.frame(x = 1:3, y = 4:6)

# Two row names for a data frame with three rows
dimnames(df) <- list(c("a", "b"), c("x", "y"))
Error in `dimnames<-.data.frame`(`*tmp*`, value = list(c("a", "b"), c("x",  :
  invalid 'dimnames' given for data frame

Check the lengths with dim(df) and pass a list with both vectors, such as dimnames(df) <- list(c("a", "b", "c"), c("x", "y")), or set row and column names separately with rownames and colnames, which give clearer error messages.