Arrays can have names
as well. Almost everything can have names
in R
. The simplest way to think about these issues is as follows: names
refers to the element name of the object. E rownames
and colnames
are names of the dimensions of the object.
Vectors, Arrays and Arrays
For example, in a vector, names
gives a name to each element of the vector.
x <- 1:10
names(x) <- paste0("elemento", 1:10)
x
elemento1 elemento2 elemento3 elemento4 elemento5 elemento6 elemento7 elemento8
1 2 3 4 5 6 7 8
elemento9 elemento10
9 10
And now you can use the name to select the element:
x["elemento1"]
elemento1
1
An array (or an array) is nothing more than a vector with one more attribute: dimensions . Let's transform the x
vector above into a 2 x 5 matrix. You can now name all array elements with names, as well as name the dimensions, that is, rows and columns, using rownames
and colnames
respectively:
dim(x) <- c(2, 5)
names(x) <- paste0("elemento", 1:10)
rownames(x) <- paste0("linha", 1:2)
colnames(x) <- paste0("coluna", 1:5)
x
coluna1 coluna2 coluna3 coluna4 coluna5
linha1 1 3 5 7 9
linha2 2 4 6 8 10
attr(,"names")
[1] "elemento1" "elemento2" "elemento3" "elemento4" "elemento5" "elemento6"
[7] "elemento7" "elemento8" "elemento9" "elemento10"
Now you can subset the names of both elements and dimensions:
x["elemento10"]
elemento10
10
x[,"coluna5"]
linha1 linha2
9 10
Matrices have only two dimensions. For more than two dimensions we have the array. Let's transform the previous array into an array 2 X 5 x 1. With the array you can continue using rownames
and colnames
to name the first and second dimension. To name the third dimension, you will use dimnames
:
dim(x) <- c(2, 5, 1)
names(x) <- paste0("elemento", 1:10)
rownames(x) <- paste0("linha", 1:2)
colnames(x) <- paste0("coluna", 1:5)
dimnames(x)[[3]] <- "terceira dimensão"
x
, , terceira dimensão
coluna1 coluna2 coluna3 coluna4 coluna5
linha1 1 3 5 7 9
linha2 2 4 6 8 10
attr(,"names")
[1] "elemento1" "elemento2" "elemento3" "elemento4" "elemento5" "elemento6" "elemento7" "elemento8"
[9] "elemento9" "elemento10"
The dimanames
is the primitive function for dimensions. So obviously you could name both rows and columns also with dimnames
.
# Nomeando linhas e colunas usando dimnames
dimnames(x)[[1]] <- paste0("linha", 1:2)
dimnames(x)[[2]] <- paste0("coluna", 1:5)
Lists and data.frames
If you create the list z <- list(a = 1, b = "c", c = 1:3)
, note that its elements have the names a
, b
and c
, and this is what the names return.
names(z)
[1] "a" "b" "c"
The data.frame is a list too, with a row.names
attribute and with the restriction that all elements must be the same size. Let's turn z
into a data.frame:
z <- as.data.frame(z)
a b c
1 1 c 1
2 1 c 2
3 1 c 3
It is now clear why no data.frame
names
is equal to colnames
. This is because the data.frame is nothing more than a list and the columns are the elements of the list.
Finally, factors are vectors, and can have names
normally.