【问题标题】:How to assign to array without changing it dimensions in R (without S4)?如何在不更改 R 中的维度(没有 S4)的情况下分配给数组?
【发布时间】:2013-02-11 16:10:45
【问题描述】:

假设我有以下对象:

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 一些类,如“MyClassArray”,并通过适当的检查重载赋值运算符,但通过快速谷歌搜索,似乎不建议甚至可能重载“

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

【问题讨论】:

  • 它对我来说很好X$A &lt;- 4。你有什么错误?以及为什么在同一个例子中使用xX
  • 是的 X$A

标签: r class operator-overloading variable-assignment


【解决方案1】:

使用[&lt;-,像这样:

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.

【讨论】:

  • 是的,但我希望这种行为是该对象的默认行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
  • 2020-01-12
相关资源
最近更新 更多