I'm struggling writing functions for my own class. Hadley Wickham suggests to implement functions for square bracket functions like [
, [<-
etc. But how is this done?
After the comment from r.user.05apr, I manage to write
`[.test` <- function(x, y){
substr(x, start = y[1], stop = y[length(y)])
}
foo <- "hello world"
class(foo) <- "test"
foo[2:5] #what correctly returns "ello"
I did find sites on how they are called, but no explanations and examples on how they are defined. For example for the mentioned [<-
function I guess, three arguments are needed, the object to manipulate, the index showing which elements of the objects shall be replaced and finally a replacement. I managed to get the result wanted by
`[<-.test` <- function(obj, index, value){
tmp <- unlist(strsplit(obj, ""))
tmp[index] <- value
return(paste(tmp, collapse = ""))
}
foo <- "hello world"
class(foo) <- "test"
foo[c(2, 5)] <- "X"
but only after figuring out that the third element has to be called value
and nothing else. So I'm looking for a good, easy to understand (this criteria is not met by Writing R Extensions; more like Creating R Packages by Friedrich Leisch) piece of literature covering the methods mentioned by Wickham.