What does "foo() <-" mean in R?

Asked

Viewed 90 times

2

Consider the vector k class factor three-tiered (1, 2 and 3):

k <- as.factor(x = sample(x = 1:3, size = 30, replace = TRUE))

 [1] 3 1 1 2 1 1 3 2 3 3 1 2 3 3 2 2 2 1 3 1 2 2 1 3 1 1 3 2 1 1
Levels: 1 2 3

length(table(k))
[1] 3

Now, I use the code below to assign you one more level (99):

levels(k) <- c(levels(k), 99)

 [1] 3 1 1 2 1 1 3 2 3 3 1 2 3 3 2 2 2 1 3 1 2 2 1 3 1 1 3 2 1 1
Levels: 1 2 3 99

length(table(k))
[1] 4
  • What does it mean foo() <-? When using this structure?
  • 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 a class(k) <- "integer" and see that the class and attribute changes class.

  • Are you looking for of this question in the English OS?

1 answer

4


Short answer

foo(obj) <- valor is the form of Rdefining 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"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.