[R] help
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Mon Sep 5 17:11:28 CEST 2005
On 05-Sep-05 Dominique Katshunga wrote:
> Dear helpeRs,
> I seem to be a little bit confused on the result I am getting from the
> few codes below:
>> u=v=seq(0,1,length=30)
>> u
> [1] 0.00000000 0.03448276 0.06896552 0.10344828 0.13793103 0.17241379
> [7] 0.20689655 0.24137931 0.27586207 0.31034483 0.34482759 0.37931034
> [13] 0.41379310 0.44827586 0.48275862 0.51724138 0.55172414 0.58620690
> [19] 0.62068966 0.65517241 0.68965517 0.72413793 0.75862069 0.79310345
> [25] 0.82758621 0.86206897 0.89655172 0.93103448 0.96551724 1.00000000
>> v
> [1] 0.00000000 0.03448276 0.06896552 0.10344828 0.13793103 0.17241379
> [7] 0.20689655 0.24137931 0.27586207 0.31034483 0.34482759 0.37931034
> [13] 0.41379310 0.44827586 0.48275862 0.51724138 0.55172414 0.58620690
> [19] 0.62068966 0.65517241 0.68965517 0.72413793 0.75862069 0.79310345
> [25] 0.82758621 0.86206897 0.89655172 0.93103448 0.96551724 1.00000000
>> f=function(x,y){cp=max(x+y-1,0)}
>> z=outer(u,v,f)
> z is a 30x30 matrix which is fine, but why all its entries are equal to
> 1? for example, the maximum between u[22]+v[22]-1 and 0 is not 1?? I
> don't really know where I went wrong!
> thanks,
> Dominique
A trap easy to fall into!
First, note from "?outer" that "FUN" must be a function which
"operates elementwise on arrays". In other words, given two
array arguments (x,y), for each element of x and the corresponding
element of y, it returns a value.
However, 'max' is not such a function (despite intuitive expectations).
Specifically:
max(u+v-1,0)
[1] 1
In other words, 'max' is like 'sum': it evaluates a single result
for the whole array. However, if you look at "?max" and read far
enough, you will find 'pmax' -- "parallel maximum" -- which does
it element by element.
Look at
pmax(u+v-1,0)
So try
f<-function(x,y){pmax(x+y-1,0)}
outer(u,v,f)
The reason this is a trap is that without looking at the code for
'outer' one might perhaps expect that 'outer' picks in turn each
possible pair of values (u[i],v[j]) and passes this pair as a
set of two numbers (x,y) to f(x,y). This is not so: it passes the
entire array of pairs all at once. When "FUN" is 'max' it returns the
maximum of this entire array for each position in the array!
Look at the code for 'outer' to see how this happens: just enter
outer
The clue is in the line
robj <- array(FUN(X, Y, ...), c(dX, dY))
Best wishes,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 05-Sep-05 Time: 16:11:22
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list