Hi
I am having difficulty with apply(). I want apply() to return a
matrix, but sometimes a vector is returned.
Toy example follows.
Function jj() takes a couple of matrices m1 and m2 as arguments
and returns a matrix with r rows and c columns where r=nrow(m2)
and c=nrow(m1).
jj <- function(m1,m2,f,...){
apply(m1, 1, function(y) {
apply(m2, 1, function(x) {
f(x, y, ...)
})
})
}
R> jj(matrix(1:20,4,5),matrix(1:10,2,5),f=sum)
[,1] [,2] [,3] [,4]
[1,] 70 75 80 85
[2,] 75 80 85 90
intended behaviour: matrix returned. [eg, 70 = sum(m1[1,],m2[1,]) ]
R> jj(matrix(1:20,4,5),matrix(1:5,1,5),f=sum)
[1] 60 65 70 75
R>
not intended behaviour: vector returned.
How do I rewrite jj() so that it consistently returns a matrix?
--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
tel 023-8059-7743
G'day Robin,>>>>> "RH" == Robin Hankin <r.hankin at noc.soton.ac.uk> writes:RH> How do I rewrite jj() so that it consistently returns a RH> matrix? How about explicitly returning a matrix with the desired dimensions?> jjfunction(m1,m2,f,...) matrix(apply(m1, 1, function(y) apply(m2, 1, function(x) f(x, y, ...) )), nrow=nrow(m2), ncol=nrow(m1))> jj(matrix(1:20,4,5),matrix(1:10,2,5),f=sum)[,1] [,2] [,3] [,4] [1,] 70 75 80 85 [2,] 75 80 85 90> jj(matrix(1:20,4,5),matrix(1:5,1,5),f=sum)[,1] [,2] [,3] [,4] [1,] 60 65 70 75 Or, using the outer command:> jjfunction(m1,m2,f,...) outer(1:nrow(m2), 1:nrow(m1), function(i,j) apply(cbind(i,j), 1, function(ii) f(m2[ii[1],], m1[ii[2],], ...)))> jj(matrix(1:20,4,5),matrix(1:10,2,5),f=sum)[,1] [,2] [,3] [,4] [1,] 70 75 80 85 [2,] 75 80 85 90> jj(matrix(1:20,4,5),matrix(1:5,1,5),f=sum)[,1] [,2] [,3] [,4] [1,] 60 65 70 75 Cheers, Berwin