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
  • 801
  • 2
  • 11
  • 32
  • 1
    Perhaps `setNames(list('foo'=2, boo=3), c('moo', 'doo'))` – akrun Apr 06 '15 at 17:13
  • 2
    `names` and `names<-` are actually different functions. They are generics, so you can define methods for them. – Roland Apr 06 '15 at 17:15
  • 1
    @Roland as I understand from your comment there is a function `names<-` which is used to change names attribute. I will be thank full if you told me how to create any function lets say `func<-` so that I can change other attributes. – Polla A. Fattah Apr 06 '15 at 17:22
  • 4
    I guess you might be looking for something like: `second = function(x) x[2]; "second<-" = function(x, value) { x[2] = value; x }`. `xx = 1:3; second(xx); second(xx) = 4; xx` – alexis_laz Apr 06 '15 at 17:43
  • 1
    @alexis_laz Nice. I hope you don't mind me including this in my answer. – Roland Apr 06 '15 at 17:49

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
  • 127,288
  • 10
  • 191
  • 288
  • 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