【发布时间】:2020-06-17 02:37:57
【问题描述】:
对于 R 中的新对象,如何指定对下标元素的赋值?如object[3] <- new value。这是我遇到的问题的一个具体示例。
# Rectangle example:
Rectangle <- function(a, b,...){
R <- list(a=a, b=b, others=list(...))
structure(R, class="Rectangle")
}#
`[.Rectangle` <- function(R,ind){
if(ind==1) return(R$a)
if(ind==2) return(R$b)
if(ind>=3) return(R$others[[ind-2]])
}#
R <- Rectangle(2,3,"other1","other2")
> R[1]; R[2]; R[3]; R[4];
[1] 2
[1] 3
[1] "other1"
[1] "other2"
> R[4] <- "new.other";
> R[1]; R[2]; R[3]; R[4];
[1] 2
[1] 3
[1] "other1"
[1] "other2"
显然,对下标对象的赋值没有奏效。我想知道正确定义此类分配的语法。也就是说,我需要以下示例:
`[<-.Rectangle` <- function(){ }
非常感谢。
【问题讨论】:
标签: r oop subset variable-assignment subscript