VFreguglia
VFreguglia

Reputation: 2311

What is printed when you call an object in R?

When you call an object, as in

x = 6
x

is there a method that is called to decide what is going to be printed in the console? Take lm objects as an example, when you call a lm, just some elements of the list (the object structure is a list) in a special formatting.

lm(cars$dist~cars$speed)

#Call:
#lm(formula = cars$dist ~ cars$speed)
#
#Coefficients:
#(Intercept)   cars$speed  
#    -17.579        3.932  

How can I modify how objects of a certain class are printed when the object is called, for example, if I wanted a result like

lm(cars$dist~cars$speed)
#cars$dist = -17.579 + 3.932*cars$speed

Edit: So based on the comments and some testing, I was thinking calling x and print(x) would have the same output. But I tried modifying the print method for the lm class.

setMethod("print", signature = "lm", function(x) print(x$coef))

which resulted in a different printing format, working as expected

print(lm(cars$dist~cars$speed))
#(Intercept)  cars$speed 
# -17.579095    3.932409 

But on the other hand, when I call

lm(cars$dist~cars$speed)
#
#Call:
#lm(formula = cars$dist ~ cars$speed)
#
#Coefficients:
#(Intercept)   cars$speed  
#    -17.579        3.932  

Shouldn't print(object) have the same result as object?

Upvotes: 1

Views: 386

Answers (1)

AdamO
AdamO

Reputation: 4910

Neither lm nor print are part of the S4 system, so "SetMethod" is the wrong syntax. If instead you use the S3 syntax:

print.lm <- function(x) print(x$coef)

It does as you say (e.g. fit <- lm(cars$dist ~ cars$speed) yields the same results when calling print(fit) and just fit).

Upvotes: 2

Related Questions