重载下标运算符"["

Pav*_*ili 10 r operator-overloading subscript subscript-operator

我试图为"["我创建的自定义类重载下标operator().我想弄清楚如何处理以下问题.

  • 你怎么能弄清楚操作员是在lhs还是rhs?即a[x] = foovsfoo = a[x]
  • 订阅整个维度时,foo = a[,x]如何识别第一个参数?
  • 当使用[seq(x,y)]时,它似乎正在扩展整个序列.有没有简单的方法来获得第一个,步骤和最后的值而不扩展?

编辑:我的第一点已收到多个答案.在这个过程中,我找到了第二个问题的答案.您可以使用"缺失"功能来确定存在哪些参数.

这是一个示例代码:

setMethod("[", signature(x="myClass"),
          function(x, i, j, k, l) {
              if (missing(i)) { i = 0 }
              if (missing(j)) { j = 0 }
              if (missing(k)) { k = 0 }
              if (missing(l)) { l = 0 }
          })
Run Code Online (Sandbox Code Playgroud)

我接受了这个问题的答案,因为第3点对我来说是最不重要的.

ags*_*udy 9

发现Generic,以便了解您的目标:

getGeneric('[')
# standardGeneric for "[" defined from package "base"
# function (x, i, j, ..., drop = TRUE) 
Run Code Online (Sandbox Code Playgroud)

而且:

getGeneric('[<-')
# standardGeneric for "[<-" defined from package "base"
# function (x, i, j, ..., value) 
Run Code Online (Sandbox Code Playgroud)

然后你像这样实现它,例如:

`[<-.foo` <-
function(x, i, j, value) 
{
       ....

}
Run Code Online (Sandbox Code Playgroud)


小智 6

对于第一个项目符号点,有两个要重载的函数:

  1. [
  2. [<-

第一个函数返回值,第二个函数设置值.请参阅文档Extract.data.frame{base}


Ari*_*man 6

请参阅源代码[.data.frame作为示例.你按顺序得到了一个x,一个i和一个aj.

> `[.data.frame`
function (x, i, j, ..... )
> `[<-.data.frame`
function (x, i, j, value) 
Run Code Online (Sandbox Code Playgroud)

你可以做类似的事情:

obj <- structure(runif(10),class="myclass")
`[.myclass` <- function(x,i=NULL,j=NULL) {
  message("First parameter is ", i, "\n")
  message("Second parameter is ", j, "\n")
    sum(x)
}
obj[c(1,2,3)]

`[<-.myclass` <- function(x,i=NULL,j=NULL,value) {
    res <- unclass(x)
    res[i] <- value
    res
}
obj[1] <- 1
Run Code Online (Sandbox Code Playgroud)

订单无关紧要.我和j是正确的:

2 -> obj[2]
> obj
 [1] 1.0000000 2.0000000 0.3466835 0.3337749 0.4763512 0.8921983 0.8643395 0.3899895 0.7773207 0.9606180
Run Code Online (Sandbox Code Playgroud)