我在为自己的班级写函数。
Hadley Wickham suggests
实现方括号函数的函数,如
[
,
[<-
等等,但这是怎么做到的?
在r.user.05apr的评论之后,我设法写了
`[.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"
我确实发现
sites on how they are called
,但没有关于如何定义它们的解释和示例。例如上述
[<-
函数我猜,需要三个参数,要操作的对象,显示对象中哪些元素应该被替换的索引,最后是替换。我设法得到了想要的结果
`[<-.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"
但只有在发现第三个元素必须被调用
value
没有别的了。所以我要找一个好的,容易理解的(这个标准不符合
Writing R Extensions
;更像
Creating R Packages by Friedrich Leisch
)关于韦翰提到的方法的文献。