[R] Calculating conditional mean of large series of experiments

Moshe Olshansky m_olshansky at yahoo.com
Fri May 30 01:25:33 CEST 2008


Your problem can be easily solved analytically
yielding that E(A/B=b) = (110 - b*b)/(21 - 2*b) - no
programming  needed!

If you insist on writing a program, you could do
something like:
x <- sample(1:10,2000,replace=TRUE)
M <- matrix(x,nrow=2)  #each column of M represents
two balls
A <- apply(M,2,max)
B <- apply(M,2,min)
S <- aggregate(A,list(B),sum)  # sum of values of A
for each value of B
n <- aggregate(B,list(B),length)  # number of
occurrences of each value of B
result <- S$x/n$x  # result[i] = E(A/B=i),
i=1,2,...,10

--- Anthony28 <argrenway at yahoo.com.au> wrote:

> 
> I need to repeat an experiment 1000 times. Each
> experiment involves randomly
> selecting one ball each from two separate bags. Each
> bag contains 10 balls,
> numbered 1, 2, 3, ... , 10. So the probability of
> selecting any one pair of
> balls is equal to all others.
> 
> For each experiment, what I need to do is assign a
> variable A which
> represents the maximum number out of the two balls
> selected; and a variable
> B which represents the minimum number out of the two
> balls. So if one
> experiment yielded (3, 9), then A = 9, B = 3.
> 
> I ultimately require the mean value of A given a
> particular value of B. As
> I'm a total novice when it comes to R (as you'll see
> below), all I have got
> so far is this:
> 
> output <- matrix(nrow=2, ncol=1000)
> 
> #I'm attempting to output a vector with 2 rows and
> 1000 columns. Each column
> represents the outcome of one experiment. I don't
> even know if what I've
> written above is allowed.
> 
> for (i in 1:1000){
> ball1 <- sample(1:10,1)
> ball2 <- sample(1:10,1)
> A <- max(ball1, ball2)
> B <- min(ball1, ball2)
> output[i] <- matrix(nrow=2, ncol=1000, data=c(A, B))
> }
> 
> # This gives me the message that "number of items to
> replace is not a
> multiple of replacement length". I would really
> appreciate it if someone
> could tell me how to do what I intended above
> properly. Also if anyone has
> time, I would like to know how to filter down the (2
> x 1000) matrix to
> contain only those elements with a particular
> B-value so that I can then
> calculate the conditional means of the A-values.
> 
> 
> -- 
> View this message in context:
>
http://www.nabble.com/Calculating-conditional-mean-of-large-series-of-experiments-tp17536218p17536218.html
> Sent from the R help mailing list archive at
> Nabble.com.
> 
> ______________________________________________
> 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