It looks like you need to understand the replacement functions. If we look at names , we also note that there is also a function names<- with the following definition:
> `names<-` function (x, value) .Primitive("names<-")
This is not very informative about what it actually does, but shows that you can write any function of the form foo<- that replaces some components of the object to which the function applies.
x <- 1:6 X <- matrix(1:9, ncol = 3) Labels <- function(obj, ...) { UseMethod("Labels") } Labels.numeric <- function(obj, ...) { names(obj) } Labels.matrix <- function(obj, which = c("colnames","rownames"), ...) { if(missing(which)) which <- "colnames" which <- match.arg(which) if(which == "colnames") { out <- colnames(obj) } else { out <- rownames(obj) } out } `Labels<-` <- function(obj, ..., value) { UseMethod("Labels<-") } `Labels<-.numeric` <- function(obj, ..., value) { names(obj) <- value obj }
What can be used as follows:
> x <- 1:6 > Labels(x) NULL > Labels(x) <- LETTERS[1:6] > x ABCDEF 1 2 3 4 5 6
The matrix method can be:
`Labels<-.matrix` <- function(obj, which = c("colnames","rownames"), ..., value) { if(missing(which)) which <- "colnames" which <- match.arg(which) if(which == "colnames") { colnames(obj) <- value } else { rownames(obj) <- value } obj }
Used as:
> Labels(X) NULL > Labels(X) <- letters[1:3] > X abc [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > Labels(X, which = "rownames") <- LETTERS[24:26] > X abc X 1 4 7 Y 2 5 8 Z 3 6 9
The trick is to remember that the replacement functions are called with the argument value , which takes the values โโfrom the right side of <- , therefore, to define your function, there must be a value argument and use this argument to set / change labels.
Of course, all this can be done using names , colnames , etc., but if you want to understand how it works, then I hope this is useful?