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?
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?
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
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.