0

Why does this code:

sapply(c(1, 3, 4, 0), print)

Returns:

[1] 1
[1] 3
[1] 4
[1] 0
[1] 1 3 4 0

Why it returns the input too?

m0nhawk
  • 22,980
  • 9
  • 45
  • 73
  • 2
    I don't understand the closure votes. The question seems entirely clear. And the explanation and comment by @David seem entirely correct. – IRTFM Oct 20 '13 at 18:51

2 Answers2

6

sapply() is returning a vector of your printed values but first printing each one as they're called. This may be more clear if you look at this example:

> x <- sapply(1:4,print)
[1] 1
[1] 2
[1] 3
[1] 4
> x
[1] 1 2 3 4
> y <- sapply(1:4,function(x) x)
> y
[1] 1 2 3 4
> identical(x,y)
[1] TRUE
David
  • 9,284
  • 3
  • 41
  • 40
  • Hmm, I'm a little confused how this example works, and I thought I understood the `apply` functions! – ChrisW Oct 20 '13 at 17:57
  • 2
    This post may help claify what the apply funtions do: http://stackoverflow.com/q/3505701/2167315 My example is just illustrating that you're seeing the each value printed individually because it is a side effect of the `print()` function. – David Oct 20 '13 at 18:01
2

This is because print prints its argument (hence the name), but it also returns them.

> x <- print( 1 )
[1] 1
> x
[1] 1

We don't see the [1] 1 usually because print returns its argument invisibly.

Romain Francois
  • 17,432
  • 3
  • 51
  • 77