[R] generate multiple probability distributions

David Carlson dcarlson at tamu.edu
Mon Dec 2 16:41:33 CET 2013


You can use recycling to simplify things:

> set.seed(42)
> x <- seq(0,12)
> bin.df <- as.data.frame(
+     rbind( cbind(x, prob=dbinom(x,12,1/6), p=1/6),
+            cbind(x, prob=dbinom(x,12,1/3), p=1/3),
+            cbind(x, prob=dbinom(x,12,1/2), p=1/2),
+            cbind(x, prob=dbinom(x,12,2/3), p=2/3)
+      ))
> bin.df$p <- factor(bin.df$p, labels=c("1/6", "1/3", "1/2",
"2/3"))
> str(bin.df)
'data.frame':   52 obs. of  3 variables:
 $ x   : num  0 1 2 3 4 5 6 7 8 9 ...
 $ prob: num  0.1122 0.2692 0.2961 0.1974 0.0888 ...
 $ p   : Factor w/ 4 levels "1/6","1/3","1/2",..: 1 1 1 1 1 1 1
1 1 1 ...
> 
> bin.df.2 <- data.frame( x, 
+     prob = c(dbinom(x,12,1/6), dbinom(x,12,1/3),
+            dbinom(x,12,1/2), dbinom(x,12,2/3)),
+     p = rep(c(1/6, 1/3, 1/2, 2/3), each=length(x))
+ )
> bin.df.2$p <- factor(bin.df$p, labels=c("1/6", "1/3", "1/2",
"2/3"))
> str(bin.df.2)
'data.frame':   52 obs. of  3 variables:
 $ x   : int  0 1 2 3 4 5 6 7 8 9 ...
 $ prob: num  0.1122 0.2692 0.2961 0.1974 0.0888 ...
 $ p   : Factor w/ 4 levels "1/6","1/3","1/2",..: 1 1 1 1 1 1 1
1 1 1 ...
> all.equal(bin.df, bin.df.2)
[1] TRUE

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352




-----Original Message-----
From: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org] On Behalf Of Michael
Friendly
Sent: Monday, December 2, 2013 8:48 AM
To: R-help
Subject: [R] generate multiple probability distributions

I want to generate a collection of probability distributions in
a data 
frame, with
varying parameters.  There must be some simpler way than what I
have below
(avoiding rbind and cbind), but I can't quite see it.

x <- seq(0,12)
bin.df <- as.data.frame(
     rbind( cbind(x, prob=dbinom(x,12,1/6), p=1/6),
            cbind(x, prob=dbinom(x,12,1/3), p=1/3),
            cbind(x, prob=dbinom(x,12,1/2), p=1/2),
            cbind(x, prob=dbinom(x,12,2/3), p=2/3)
           ))
bin.df$p <- factor(bin.df$p, labels=c("1/6", "1/3", "1/2",
"2/3"))
str(bin.df)

 > str(bin.df)
'data.frame':   52 obs. of  3 variables:
  $ x   : num  0 1 2 3 4 5 6 7 8 9 ...
  $ prob: num  0.1122 0.2692 0.2961 0.1974 0.0888 ...
  $ p   : Factor w/ 4 levels "1/6","1/3","1/2",..: 1 1 1 1 1 1 1
1 1 1 ...
 >

-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept. & Chair, Quantitative Methods
York University      Voice: 416 736-2100 x66249 Fax: 416
736-5814
4700 Keele Street    Web:   http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA

______________________________________________
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.



More information about the R-help mailing list