2014-01-06 58 views
1

我在下面使用R refClass示例。R refClass方法

Person = setRefClass("Person",fields = list(name = "character", age = "numeric") 
      ) ## Person = setRefClass("Person", 


Person$methods = list(
       increaseAge <- function(howMuch){ 
       age = age + howMuch 
       } 
     ) 

當我將此程序存儲在一個名爲Person.R的文件中並將其來源時,它不顯示任何錯誤。現在我實例化一個新的對象。

p = new("Person",name="sachin",age=40) 

我嘗試調用方法increaseAge,使用p$increaseAge(40),它顯示了以下錯誤

Error in envRefInferField(x, what, getClass(class(x)), selfEnv) : 
    "increaseAge" is not a valid field or method name for reference class "Person" 

我想不通爲什麼它說,該方法increaseAge不是有效的方法名時我已經定義了它。

回答

0

我使用你的代碼出錯。我會做這樣的事情:

Person = setRefClass("Person", 
         fields = list(name = "character", age = "numeric"), 
         methods = list(
         increaseAge = function(howMuch) age <<- age + howMuch 
        )) 

> p = new("Person",name="sachin",age=40) 
> p$increaseAge(5) 
> p$age 
[1] 45 
+0

謝謝agstudy。你的代碼也適用於我。但我不明白我的代碼有什麼問題?我注意到你使用「<< - 」而不是「=」。賦值運算符是我錯過了我的想法。 – Amit

+0

我想你應該仔細閱讀'setRefClass'的幫助。 – agstudy

2

要指定一個獨立的方法類定義,調用methods()功能發電機上。此外,還可以使用<<-.self$age =進行分配。

Person$methods(increaseAge=function(howMuch) { 
    age <<- age + howMuch 
    ## alterenatively, .self$age = age + howMuch or .self$age <- age + howMuch 
}) 

記住的是,R效果最好的載體,所以覺得Persons類(造型),代表你的學習所有的個人,而不是Person實例(模擬行)的集合。

+0

感謝您的意見。明白了。我只是過渡到爲R項目使用OOPS。這有助於。 – Amit