2016-10-06 3 views
1

콘솔에 개체 이름을 입력 할 때 인쇄 메서드가 호출되도록 R S4 개체에 대한 인쇄 방법을 만들려고합니다. print()를 명시 적으로 호출 할 때 올바른 메서드를 호출하도록 구성 할 수 있지만 화면에 개체를 입력 할 때가 아닙니다. 어떤 제안이라도 대단히 감사 할 것입니다!S3 인쇄 제네릭 호출은 명시 적으로 호출 된 인쇄 인 경우에만 S4 인쇄 방법을 호출합니다.

setClass("Person", 
    slots = list(name = "character", age = "numeric")) 

alice <- new("Person", name = "Alice", age = 40) 
print.Person <- function(x,...) print("This is a person object") 
setMethod("print","Person",print.Person) 

# Behavior that I want 
print(alice) 
[1] "This is a person object" 

# Not the behavior that I want 
alice 
An object of class "Person" 
Slot "name": 
[1] "Alice" 

Slot "age": 
[1] 40 

답변

3

나는 S4에 큰 전문가가 아니라고하지만 난 당신이 S4로, S3입니다 제네릭을 혼합해야한다고 생각하지 않습니다. show 문서에서 지적했듯이 당신이 당신의 목적을 위해 당신이 찾고있는 행동이

setClass("Person", slots = list(name = "character", age = "numeric")) 

alice <- new("Person", name = "Alice", age = 40) 

setMethod("show", "Person", 
      function(object) print(paste("This is a person object named", 
             [email protected])) 
     ) 

alice 
# [1] "This is a person object named Alice" 
print(alice) 
# [1] "This is a person object named Alice" 

을하는 방법을 정의 할 수 있습니다.