I am very new to R. Can someone kindly tell me what is going on in the following code.
a<- 1:10
b<-sapply(a, function(x) sapply(a,function(y) x+y))
b
Why does b look like this:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 2 3 4 5 6 7 8 9 10 11
[2,] 3 4 5 6 7 8 9 10 11 12
[3,] 4 5 6 7 8 9 10 11 12 13
[4,] 5 6 7 8 9 10 11 12 13 14
[5,] 6 7 8 9 10 11 12 13 14 15
[6,] 7 8 9 10 11 12 13 14 15 16
[7,] 8 9 10 11 12 13 14 15 16 17
[8,] 9 10 11 12 13 14 15 16 17 18
[9,] 10 11 12 13 14 15 16 17 18 19
[10,] 11 12 13 14 15 16 17 18 19 20
By the time the individual items of two versions of the a-vector arrive at the inner expression, they cover the range of the possible pairings of the first 10 positive integers. It's basically the same as two nested for-loops. The sapply function will return a matrix if possible. The inner sapply returns a series of length 10 vectors and the outer sapply assembles the vectors into a matrix. You could also have returned the same result with:
outer( 1:10, 1:10, "+")
I do not really agree with Scriven that this form is "nonsense". If one were using the sum function, then the outer strategy would not succeed. The sum function is not 'vectorized' (at least in the way that function is used by R users) since it does usually not return a value of the same length as its arguments. Nonetheless the double-sapply approach would give the same results with sum(x,y) as the inner expression, whereas outer(a,a,'sum') will fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With