[R] simple apply syntax
Prof Brian Ripley
ripley at stats.ox.ac.uk
Sun Jul 11 10:02:01 CEST 2010
On Sun, 11 Jul 2010, Robin Jeffries wrote:
> I know this is a simple question, but I have yet to master the apply
> statements. Any help would be appreciated.
You don't want to use apply() here: rbinom is vectorized. However, you
cannot use mat$x on a matrix, and the cbind() gave you a matrix
anyway. So something like
mat <- data.frame(p=runif(10,0,1), n=rep(1:5))
mat$x <- with(mat, rbinom(10, n, p))
is the idiomatic way to do it.
As an example of using apply and a matrix:
mat <- cbind(p=runif(10,0,1), n=rep(1:5))
x <- apply(mat, 1, function(z) rbinom(1, z['n'], z['p']))
mat <- cbind(mat, x=x)
> I have a column of probabilities and sample sizes, I would like to create a
> column of binomial random variables using those corresponding probabilities.
>
> Eg.
>
> mat = as.matrix(cbind(p=runif(10,0,1), n=rep(1:5)))
>
>
>
> p n
>
> [1,] 0.5093493 1
>
> [2,] 0.4947375 2
>
> [3,] 0.6753015 3
>
> [4,] 0.8595729 4
>
> [5,] 0.1004739 5
>
> [6,] 0.6292883 1
>
> [7,] 0.3752004 2
>
> [8,] 0.6889157 3
>
> [9,] 0.2435880 4
>
> [10,] 0.9619128 5
>
>
>
>
>
> I want to create mat$x as binomial(n, p)
>
>
>
> Thanks,
>
> Robin
>
>
> [[alternative HTML version deleted]]
Please so as we ask, and don't send HTML but rather properly formatted
plain text (without all these blank lines).
>
> ______________________________________________
> R-help at 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.
>
--
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 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list