3

In R language there are some functions like names and dimnames which you can assign values to them as example:

x <- list('foo'=2, boo=3)
names(x) # This returns ("foo", "boo") vector
names(x) <- c("moo", "doo") # Changes existing item names to ("moo", "doo")

My question is how to create such functions which apparently they act as set and get functions at the same time.

Polla A. Fattah
  • 751
  • 2
  • 9
  • 31

1 Answers1

6

You encountered a special kind of function. From the language definition (section 3.1.3 Function calls):

A special type of function calls can appear on the left hand side of the assignment operator as in

class(x) <- "foo"

What this construction really does is to call the function class<- with the original object and the right hand side. This function performs the modification of the object and returns the result which is then stored back into the original variable. (At least conceptually, this is what happens. Some additional effort is made to avoid unnecessary data duplication.)

Such functions are .Primitive functions. They call internal C code. Usually they are generic functions, which means you can define methods for them.

@alexis_laz demonstrates how to create such a function in his comment:

second <- function(x) x[2]
"second<-" <- function(x, value) { x[2] <- value; x }
xx <- 1:3
second(xx)
#[1] 2
second(xx) <- 4
xx
#[1] 1 4 3
Community
  • 1
  • 1
Roland
  • 122,144
  • 10
  • 182
  • 276
  • Thank you. while this is not a solution but it might be a good indication that I should stop searching any more in this direction. – Polla A. Fattah Apr 06 '15 at 17:45
  • That was what I looking for so many thanks to you to point out that I need this kind of function and thanks to @alexis_laz as he showed me how to create it. – Polla A. Fattah Apr 06 '15 at 17:58