从ReferenceClass方法返回data.table的副本

时间:2013-05-15 13:11:16

标签: r data.table reference-class

我尝试从ReferenceClass的方法中返回data.table s的副本:

dummy <- setRefClass(
  "dummy",
  fields = list(
    dt = "data.table"
  ),
  methods = list(
    initialize = function( df ){
      if( !missing( df ) ){
        dt <<- data.table( df , key = "a" )
      }
    },
    getTab = function( ix ){
      return( copy(dt[ ix, ]) )
    }
  )
)

然而,调用dummy$getTab()会产生一个我不明白的错误:

d <- dummy$new( data.frame( a = 1:10, b = 1:10 ) )
d$getTab( 2:5 )

Error in if (shallow) assign(field, get(field, envir = selfEnv), envir = vEnv) else { : 
  argument is not interpretable as logical
In addition: Warning message:
In if (shallow) assign(field, get(field, envir = selfEnv), envir = vEnv) else { :
 the condition has length > 1 and only the first element will be used

我不知道它是什么意思,它来自何处。另外,以下两个程序没有任何问题:

copy( d$dt[ 2:5 ] )

mycopy <- function( dt, ix ) {
  return( copy(dt[ ix, ]) )
}
mycopy( d$dt, 2:5 )

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

好的抱歉,这是一个愚蠢的错误,我只是监督了方法envRefClass$copy()。因此,解决方案是明确调用data.table::copy

dummy <- setRefClass(
  "dummy",
  fields = list(
    dt = "data.table"
  ),
  methods = list(
    initialize = function( df ){
      if( !missing( df ) ){
        dt <<- data.table( df , key = "a" )
      }
    },
    getTab = function( ix ){
      return( data.table::copy(dt[ ix, ]) )
    }
  )
)