[R] creating a grid of function values

Prof Brian D Ripley ripley at stats.ox.ac.uk
Thu Feb 10 23:00:13 CET 2000


On 10 Feb 2000, Douglas Bates wrote:

> I want to create a grid of function values for use in `contour' or
> `persp'.  The function is the log-likelihood for the gamma.  The
> sample is stored as vector of length 20 called `Survival'.
> 
> A single evaluation of the log-likelihood at, say, scale = 9 and shape
> = 10 would be obtained by
>  sum(dgamma(Survival, scale = 9, shape = 10, log = TRUE))
> (This may work only 0.99.0, I'm not sure.)
> 
> I would like to evaluate such a function on a grid of scale and shape
> values.  I don't think I can use `outer' because of the way the
> evaluation of the dgamma function would vectorize.  Although I could

It should vectorize correctly if we use three dimensions. Let's see:

Survival <- rgamma(20, 5, 5)

res <- do.call("dgamma", expand.grid(x=Survival, scale=8:12, 
shape=7:12, log=1))
# avoid conversion of logicals to factor here.

dim(res) <- c(length(Survival), 5, 6)

> apply(res, c(2,3), sum)
          [,1]      [,2]      [,3]      [,4]      [,5]      [,6]
[1,] -121.0935 -141.6717 -164.9205 -190.5250 -218.2367 -247.8546
[2,] -131.1431 -154.0770 -179.6815 -207.6417 -237.7090 -269.6826
[3,] -140.7416 -165.7827 -193.4944 -223.5618 -255.7364 -289.8171
[4,] -149.8698 -176.8171 -206.4350 -238.4086 -272.4894 -308.4764
[5,] -158.5387 -187.2262 -218.5844 -252.2982 -288.1192 -325.8464


Actually, I would use

sc <- 8:12; sh <- 7:12
args <- expand.grid(scale=sc, shape=sh)

matrix(apply(args, 1, function(x) sum(dgamma(Survival, scale=x[1],
shape=x[2], log=T))), length(sc), dimnames=list(scale=sc, shape=sh))

     shape
scale         7         8         9        10        11        12
   8  -121.0935 -141.6717 -164.9205 -190.5250 -218.2367 -247.8546
   9  -131.1431 -154.0770 -179.6815 -207.6417 -237.7090 -269.6826
   10 -140.7416 -165.7827 -193.4944 -223.5618 -255.7364 -289.8171
   11 -149.8698 -176.8171 -206.4350 -238.4086 -272.4894 -308.4764
   12 -158.5387 -187.2262 -218.5844 -252.2982 -288.1192 -325.8464

Brian

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list