2

Sometimes I read posts where people use the print() function and I don't understand why it is used. Here for example in one answer the code is

print(fitted(m))
#         1         2         3         4         5         6         7         8 
# 0.3668989 0.6083009 0.4677463 0.8685777 0.8047078 0.6116263 0.5688551 0.4909217 
#         9        10 
# 0.5583372 0.6540281 

But using fitted(m) would give the same output. I know there are situations where we need print(), for example if we want create plots inside of loops. But why is the print() function used in cases like the one above?

  • 3
    I guess for didactic reasons (to make it obvious that this code is intended to print). There used to be rare cases (hopefully fixed successfully with the current R version), where `print` and auto-printing did not print exactly the same result but the linked example probably wasn't one of them. – Roland Jul 11 '19 at 09:05

2 Answers2

4

I guess that in many cases usage of print is just a bad/redundant habit, however print has a couple of interesting options:

Data:

x <- rnorm(5)
y <- rpois(5, exp(x))
m <- glm(y ~ x, family="poisson")
m2 <- fitted(m)
#         1         2         3         4         5 
# 0.8268702 1.0523189 1.9105627 1.0776197 1.1326286 

digits - shows wanted number of digits

print(m2, digits = 3) # same as round(m2, 3)
#     1     2     3     4     5 
# 0.827 1.052 1.911 1.078 1.133 

na.print - turns NA values into a specified value (very similar to zero.print argument)

m2[1] <- NA
print(m2, na.print = "Failed")
#        1        2        3        4        5 
#   Failed 1.052319 1.910563 1.077620 1.132629 

max - prints wanted number of values

print(m2, max = 2) # similar to head(m2, 2)
#        1        2 
#       NA 1.052319 
pogibas
  • 27,303
  • 19
  • 84
  • 117
2

I'm guessing, as I rarely use print myself:

  • using print() makes it obvious which lines of your code do printing and which ones do actual staff. It might make re-reading your code later easier.
  • using print() explicitly might make it easier to later refactor your code into a function, you just need to change the print into a return
  • programmers coming from a language with strict syntax might have a strong dislike towards the automatic printing feature of r
Tamás Bárász
  • 352
  • 3
  • 6