如何分配给数组而不改变R中的尺寸(没有S4)?

时间:2013-02-26 09:15:13

标签: r class operator-overloading variable-assignment

假设我有以下对象:

X<-NULL
X$y<-1:10
X$A<-array(1:15,c(3,3,5))
attr(X,"Adim1")<-3
attr(X,"Adim2")<-5
class(X)<-"MyClass"

现在我想更改X$A的值,而无需更改维度,即我希望X$A具有以下属性

# This should work
    X$A<- array(1,c(3,3,5))
# This should give an error or be identical with  X$A[]<-4 i.e. X$A<- array(4,c(3,3,5))
    X$A<- 4 
#Actually it should be possible to change the last dimension to 1 but that's just some sugar:
    X$A<- array(1,c(3,3,1))

我想知道这种行为可以做些什么吗?我正在考虑给x $ A一些像#34; MyClassArray&#34;并通过适当的检查使赋值运算符超载,但通过快速搜索,似乎不建议甚至可能超载&#34;&lt; - &#34;运营商。那么还有其他选择吗?

我知道可以使用S4类完成,但我不想混合使用S3和S4。

1 个答案:

答案 0 :(得分:0)

使用[<-,如下所示:

X <- NULL
X$A <- array(1:15,c(3,3,5))
X$A[] <- 4
X


$A
, , 1

     [,1] [,2] [,3]
[1,]    4    4    4
[2,]    4    4    4
[3,]    4    4    4

, , 2

     [,1] [,2] [,3]
[1,]    4    4    4
[2,]    4    4    4
[3,]    4    4    4

... etc.