y <- 1:10
# set attributes
attr(y, "my_attr") <- "This is a vector"
# get attributes
attr(y, "my_attr")
#> [1] "This is a vector"
# get all attributes as a list
attributes(y)
#> $my_attr
#> [1] "This is a vector"
str(attributes(y))
#> List of 1
#> $ my_attribute: chr "This is a vector"
The structure()
function returns a new object with modified attributes:
structure(1:10, my_attr = "This is a vector")
#> [1] 1 2 3 4 5 6 7 8 9 10
#> attr(,"my_attribute")
#> [1] "This is a vector"
The only attributes not lost are the 3 most important:
- Names, a character vector giving each element a name, described in names.
- Dimensions, used to turn vectors into matrices and arrays, described in matrices and arrays.
- Class, used to implement the S3 object system, described in S3.
Each of these attributes has a specific accessor function to get and set values. When working with these attributes, use names(x)
, dim(x)
, and class(x)
, not attr(x, "names")
, attr(x, "dim")
, and attr(x, "class")
.
names
You can name a vector in three ways: \index{attributes|names}
- When creating it:
x <- c(a = 1, b = 2, c = 3)
. - By modifying an existing vector in place:
x <- 1:3; names(x) <- c("a", "b", "c")
. - By creating a modified copy of a vector:
x <- 1:3
setNames(x, c("a", "b", "c") )
# this is just a short form of
names(x) <- c("a", "b", "c")
Names don't have to be unique. However, character subsetting, described in subsetting, is the most important reason to use names and it is most useful when the names are unique.
Not all elements of a vector need to have a name. If some names are missing, names()
will return an empty string for those elements. If all names are missing, names()
will return NULL
.
y <- c(a = 1, 2, 3)
names(y)
z <- c(1, 2, 3)
names(z)
You can create a new vector without names using unname(x)
, or remove names in place with names(x) <- NULL
.