On 28/06/2012 10:39, dj hawthorne wrote:
Greetings,
I am trying to understand how to making a subset assignment function.
Take the example where of making a "last" generic function.
last <- function(x,...) UseMethod("last");
last.numeric <- function(x, ...) x[length(x)]
last.list <- function(x, ...) x[[length(x)]]
.....
Now we run into the problem at hand if we want to assign something to the
last item. Of course we could define a separate setter function, but I am
not interested in this problem specifically, but understanding the method
that would let me write the function to allow the following reasonable
behavior.
vec <- 1:5
last(vec)<-10
vec $ 10
[Dunno what the last means: it is not valid R syntax.]
To do that you define a replacement function (not a 'setter function').
Most of those in R are primitive, but here's an example:
`last<-` <- function(x, value) UseMethod("last<-")
`last<-.default` <- function(x, value) { x[length(x)] <- value; x }
`last<-.list` <- function(x, value) { x[l[ength(x)]] <- value; x }
Thank you for your time and expertise!
--
Brian D. Ripley, rip...@stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.