Rows and columns Names in R objects

Lists can have named items in the list.

Matrices and data.frame can have named rows and columns.

Setting column and row names

On a list

Only the names function is available to rename the elements of the list:

> pts = list(x=c(1,2,3), y=c(5,6,3))
> names(pts)
[1] "x" "y"
> dimnames(pts)
NULL

On a matrix

Functions row.names, colnames and dimnames (if used, it must be set to a list with as many elements as dimensions) can be used.

> x = matrix(1:9,3,3)
> row.names(x)
NULL
> colnames(x)
NULL
> names(x)
NULL
> colnames(x) = c("a","b","c")
> row.names(x) = c("e","f", "g")
> names(x)
NULL
> x
  a b c
e 1 4 7
f 2 5 8
g 3 6 9
> dimnames(x)
[[1]]
[1] "e" "f" "g"
[[2]]
[1] "a" "b" "c"

Note that the function names can also be use on a matrix to rename the columns.

On a data.frame

The same functions as with the matrix apply but the dimnames are set by default when the data.frame is created.

 

Matthieu Liatard
Remember this!
Remember this
Play!
Take a quizz on this subject
Close

Hello :)
At Question-Player, we want to share more knowledge and help you never forget anything ever. And for free.

To show us your support, you can create an account:

Login / Create an account
Rate this article :
1
2
3
4
5

Up next

Related posts