对于R中的新对象,如何通过下标分配值?

问题描述 投票:0回答:2

对于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
2个回答
0
投票

也许这可以帮助您:


0
投票

要覆盖子集分配,您的函数需要接受三个参数(x, index, value)并返回修改后的对象。重要的是第三个参数称为exactly

© www.soinside.com 2019 - 2024. All rights reserved.