Short answer
foo(obj) <- valor
is the form of R
defining valor
as an attribute foo
of the object obj
.
Long answer
This is a very common way of defining some attributes of an object. It is common for the attribute functions of an object to come "in pairs": one to read the attribute and one to define these attributes. We can see this with row.names()
, names()
, levels()
, etc..
Let’s take a few examples:
row.names(head(mtcars))
#> [1] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Hornet 4 Drive"
#> [5] "Hornet Sportabout" "Valiant"
names(iris)
#> [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
For each of these functions there is a function foo<-
. Let’s see:
`names<-` # é importante colocar os "`"s.
#> function (x, value) .Primitive("names<-")
This "version" of the functions does not only allow you to "read" the attribute, but assigns it. So we have, for example
iris2 <- iris
names(iris2)
#> [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
names(iris2)[3] <- "terceira_coluna"
names(iris2)
#> [1] "Sepal.Length" "Sepal.Width" "terceira_coluna" "Petal.Width"
#> [5] "Species"
To implant one of these pairs, we would have something like this:
sobrenome <- function(obj) {
attributes(obj)[["sobrenome"]]
}
`sobrenome<-` <- function(obj, value) {
antigo <- attributes(obj)
antigo$sobrenome <- value
attributes(obj) <- antigo
obj
}
meu_nome <- "Tomas"
sobrenome(meu_nome)
#> NULL
sobrenome(meu_nome) <- "Barcellos"
sobrenome(meu_nome)
#> [1] "Barcellos"
From what I understand this type of function is to rewrite the attributes. If you give a
attributes(k)
will see the existing attributes for factors. You can try aclass(k) <- "integer"
and see that the class and attribute changesclass
.– Jorge Mendes
Are you looking for of this question in the English OS?
– Rui Barradas