Pav*_*ili 10 r operator-overloading subscript subscript-operator
我试图为"["我创建的自定义类重载下标operator().我想弄清楚如何处理以下问题.
a[x] = foovsfoo = a[x] foo = a[,x]如何识别第一个参数?编辑:我的第一点已收到多个答案.在这个过程中,我找到了第二个问题的答案.您可以使用"缺失"功能来确定存在哪些参数.
这是一个示例代码:
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点对我来说是最不重要的.
发现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)
请参阅源代码[.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)
| 归档时间: |
|
| 查看次数: |
1543 次 |
| 最近记录: |