0

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.

Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • 1
    `\`[.test`\` maybe? – r.user.05apr Nov 08 '18 at 09:10
  • Thank you this help for the first problem, but I realized my problem is broader: I'm looking for some kind of literature to learn how these functions are build correctly. I changed the question therefore. – Qaswed Nov 08 '18 at 10:07

0 Answers0