The Art of R Programming

(WallPaper) #1
If you really want to restrictcto scalars, you should insert some kind of
check, say this one:

>f
function(x,c) {
if (length(c) != 1) stop("vector c not allowed")
return((x+c)^2)
}

2.6.2 Vector In, Matrix Out............................................


The vectorized functions we’ve been working with so far have scalar return
values. Callingsqrt()on a number gives us a number. If we apply this func-
tion to an eight-element vector, we get eight numbers, thus another eight-
element vector, as output.
But what if our function itself is vector-valued, asz12()is here:

z12 <- function(z) return(c(z,z^2))

Applyingz12()to 5, say, gives us the two-element vector (5,25). If we
apply this function to an eight-element vector, it produces 16 numbers:

x<-1:8
> z12(x)
[1]123456781491625364964

It might be more natural to have these arranged as an 8-by-2 matrix,
which we can do with thematrixfunction:

> matrix(z12(x),ncol=2)
[,1] [,2]
[1,] 1 1
[2,] 2 4
[3,] 3 9
[4,] 4 16
[5,] 5 25
[6,] 6 36
[7,] 7 49
[8,] 8 64

But we can streamline things usingsapply()(orsimplify apply). The call
sapply(x,f)applies the functionf()to each element ofxand then converts
the result to a matrix. Here is an example:

> z12 <- function(z) return(c(z,z^2))
> sapply(1:8,z12)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]

42 Chapter 2

Free download pdf