On 08/08/2011 8:21 AM, Duncan Murdoch wrote:
On 08/08/2011 4:34 AM, Kathie wrote:
> Dear all,
>
> I am trying to use "do.call", but I don't think I totally understand this
> function.
>
> Here is an simple example.
>
> --------------------------------------------
>
> > B<- matrix(c(.5,.1,.2,.3),2,2)
> > B
> [,1] [,2]
> [1,] 0.5 0.2
> [2,] 0.1 0.3
> > x<- c(.1,.2)
> > X<- cbind(1,x)
> > X
> x
> [1,] 1 0.1
> [2,] 1 0.2
> >
> > lt<- expand.grid(i=seq(1,2), y0=seq(0,2))
> > lt
> i y0
> 1 1 0
> 2 2 0
> 3 1 1
> 4 2 1
> 5 1 2
> 6 2 2
> >
> > fc<- function(y0,i) dpois(y0, exp(rowSums(t(X[i,])*B[,1])))
> >
> > do.call(fc,lt)
> [1] 1.892179e-09 3.348160e-01 3.800543e-08 3.663470e-01 3.816797e-07
> 2.004237e-01
>
> --------------------------------------------
>
> Unfortunately, what I want to get is
>
> dpois(0, exp(rowSums(t(X[1,])*B[,1]))) = 0.1891356
> dpois(0, exp(rowSums(t(X[2,])*B[,1]))) = 0.1859965
> dpois(1, exp(rowSums(t(X[1,])*B[,1]))) = 0.3149658
> dpois(1, exp(rowSums(t(X[2,])*B[,1]))) = 0.3128512
> dpois(2, exp(rowSums(t(X[1,])*B[,1]))) = 0.2622549
> dpois(2, exp(rowSums(t(X[2,])*B[,1]))) = 0.2631122
>
> --------------------------------------------
>
> Would you plz tell me why these two results are different?? and how do I get
> what I want to using "do.call" function??
Your function expects arguments in the order y0, i, but you are passing
them in the order i, y0. Change the header of your function or the
order of the columns in lt.
Sorry, that's the wrong explanation of the problem. Since you were
using a dataframe, the arguments are named, and the order doesn't matter.
The problem is that your function fc can't handle vector arguments.
Your "do.call(fc, lt)" is the same as fc(i=lt$i, y0=lt$y0), and that
won't work. You really want some version of apply, or to use Vectorize
on your function. For example,
> fc <- Vectorize(fc)
> fc(i=lt$i, y0=lt$y0)
[1] 0.1891356 0.1859965 0.3149658 0.3128512 0.2622549 0.2631122
Duncan Murdoch
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.