[R] simple apply syntax
Joshua Wiley
jwiley.psych at gmail.com
Sun Jul 11 09:48:52 CEST 2010
Hello Robin,
I cannot quite figure out what your final goal is (it's late and I'm
low on caffeine so if I missed the obvious, bear with me). I think
you may mean the rbinom() function rather than the binomial() function
(see ?rbinom and ?binomial, respectively). At any rate, this should
get you there except for deciding what arguments of what function you
want to pass the values from your matrix to.
set.seed(1)
mat <- as.matrix(cbind(p=runif(10,0,1), n=rep(1:5)))
#demonstrating what 'x' is
apply(X = mat, MARGIN = 1, FUN = function(x)
{return(x)})
#the function I imagine you might pass x to
apply(X = mat, MARGIN = 1, FUN = function(x)
{rbinom(n = 1, size = x[2], prob = x[1])})
what I did was just create an anonymous function, with a single
argument, (x). 'x' becomes the values of each row in 'mat'. So all
you have to do then, is specify what function (e.g., rbinom() ) you
want to use, and then which arguments are set to what element of 'x'
(here 1 or 2, but there could be more if you had more columns in your
matrix).
HTH,
Josh
On Sun, Jul 11, 2010 at 12:27 AM, Robin Jeffries <rjeffries at ucla.edu> wrote:
> I know this is a simple question, but I have yet to master the apply
> statements. Any help would be appreciated.
>
> 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]]
>
> ______________________________________________
> 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.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/
More information about the R-help
mailing list