[R] Problem using outer()
John Smith
johns2326 at hotmail.com
Thu Jan 16 15:47:02 CET 2003
Here is a problem I am having. I would sincerely appreciate any help/advice
from the experts who read this list. I have contrived a simple example, but
it gives the same result I encountered in a more complicated application.
Given data frame u:
x y
31 19
32 18
33 17
34 16
35 15
36 14
37 13
I define the function f as follows:
f <- function(a,b) sum(u$x - a) + sum(u$y - b)
One might think of a and b as "mean" values, and the function f totals up
the deviations.
I wish to generate a table of the value of f given various values of a and b
along grid points. So I define:
aa <- seq(0.1,1.0,0.1)
bb <- seq(1.0,2.0,0.1)
Unfortunately, when I issue the command
s <- outer(aa,bb,f)
R tells me the following:
Warning messages:
1: longer object length
is not a multiple of shorter object length in: u$x - a
2: longer object length
is not a multiple of shorter object length in: u$y - b
Outer() does assign values to s, but they are values that do not make sense.
I understand why this is happening. Outer() passes the vectors aa and bb to
function f, where the statement sum(u$x - a) + sum(u$y - b) is encountered
with u$x and u$y of length 7 and a and b of length 10. R then cannot apply
the recycle rule.
I can do this simply enough with nested loops and get the correct answer.
Unfortunately, the "real" problem is much more involved than the simple
example I show here (data frame u contains hundreds of observations, and the
function f is many lines long) so the solution takes some time. The R
documentation stresses in a number of places that loops are inefficient and
should be eliminated where possible. I thought using outer() would speed the
application up, but it doesn't work.
Any suggestions? How can I build up the table of values without using nested
loops?
John Shonder
More information about the R-help
mailing list