【问题标题】:For new objects in R, how to assign values through subscripting?对于R中的新对象,如何通过下标赋值?
【发布时间】: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


    【解决方案1】:

    要覆盖子集分配,您的函数需要接受三个参数 (x, index, value) 并返回修改后的对象。重要的是,第三个参数准确地调用value,因为 R 在内部使用该名称(而不是位置)调用函数。

    这是一个例子:

    `[<-.Rectangle` = function (x, index, value) {
        if (index == 1L) {
            x$a = value
        }
        else if (index == 2L) {
            x$b = value
        }
        else {
            x$others[[index - 2L]] = value
        }
        x
    }
    

    不言而喻,这是一个相当复杂的逻辑,我不相信现实世界的代码应该有具有这种 API 的对象。

    【讨论】:

    • 非常感谢。这正是我所追求的。我同意你的观点,我的例子确实是非常人为的。我必须包含列表才能使分配失败,否则,它正确分配给索引 1 和 2。再次感谢。
    【解决方案2】:

    也许这对你有帮助:

    > str(R)
    List of 3
     $ a     : num 2
     $ b     : num 3
     $ others:List of 2
      ..$ : chr "other1"
      ..$ : chr "other2"
     - attr(*, "class")= chr "Rectangle"
    
    > R[4]='hello'
    > str(R)
    List of 4
     $ a     : num 2
     $ b     : num 3
     $ others:List of 2
      ..$ : chr "other1"
      ..$ : chr "other2"
     $       : chr "hello"
     - attr(*, "class")= chr "Rectangle"
    
    
    > R[4]
    [1] "other2"
    
    > R[[4]]
    [1] "hello"
    

    【讨论】:

    • 感谢您的帮助,尽管这不是我想要的。一般来说,我宁愿尝试了解[&lt;-. 的语法;而不是解决这个特定的分配问题。不过,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2017-03-28
    • 2012-07-15
    • 1970-01-01
    • 2020-02-27
    相关资源
    最近更新 更多