[R] A problem about outer()

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Mon Feb 28 17:25:19 CET 2005


You might want to read (or re-read) the posting guide about giving a
simple example. See comments below.


On Mon, 2005-02-28 at 23:03 +0800, Feng Chen wrote:
> Dear all,
> 
> I have something about function outer() that I can't understand. Just see the following example. The two NaNs are due to 0/0, but I can't figure out the cause of the last two errors. I wonder if some one can explain this for me. 
> ___________________________________________________________________
> > sx=rbinom(10,1,0.5);ot=rbinom(10,1,0.5);ag <- rbinom(10,100,0.3);ho <- rbinom(10,100,0.5)


Cute but unfortunately not very legible. Why are you mixing "=" and
"<-" ? Is there a problem with space bars and return key on your
keyboard ? Please learn to wrap the emails at about 72 characters per
line (see http://expita.com/nomime.html).


> > dp <- function(s,a,h)sum((sx==s)&(ag==a)&(ho==h)&(ot==1))/sum((sx==s)&(ag==a)&(ho==h))

> > (function(x,y)dp(1,x,y))(2,3)
> [1] NaN
> > (function(x,y)dp(0,x,y))(27,52)
> [1] NaN

Again this is confusing. Why not define another function (you will need
to anyway - see below). 

Alternatively, you can set 1 as the default value for s in dp().  

> > dpm <- outer(ag,ho,function(x,y)dp(1,x,y))
> Error in outer(ag, ho, function(x, y) dp(1, x, y)) : 
>  dim<- : dims [product 100] do not match the length of object [1]

>From help("outer") :

'FUN' must be a function (or the name of it) which expects at
least two arguments and which operates elementwise on arrays.


And following the suggestion of Prof. Daalgard in the thread
http://tolstoy.newcastle.edu.au/R/help/00a/1445.html

dp.vect <- function(s, x, y){
  sapply( 1:length(x), function(i) dp( s=s, a=x[i], h=y[i]) )
}
outer(ag, ho, FUN=dp.vect, s=1 )
# works but I leave the verification to you



Your problem could be generalised as the following example

one <- rnorm(3); two <- rnorm(4)                 # data
outer( one, two, function(x, y) x + y )          # works fine
outer( one, two, function(x, y) sum(c(x, y)) )   # does not work

sum.vect <- function(x, y){
  sapply( 1:length(x), function(i) sum( c( x[i], y[i] ) ) )
}
outer( one, two, sum.vect )



> > dpf <- outer(ag,ho,function(x,y)dp(0,x,y))
> Error in outer(ag, ho, function(x, y) dp(0, x, y)) : 
>  dim<- : dims [product 100] do not match the length of object [1]
> > 
> -------------------------------------------------------------------------------------------------------------------
> 
> Thanks very much,
> Feng
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list