# Observations with probability in R

#### Rlanguagestatistictrainee

##### New Member
Hello, please assist me in answering the following question involving R code and statistics.

Loop through
CoinTosses<-matrix(nrow=5000,ncol=20)
to simulate for each column, 50 coin tosses where a
toss has a probability of heads, from 0.05
to 1 probability in each column respectively. Coin 1 in
column 1, will have 50 tosses where heads come up
with probability 0.05, and Coin 20 will obtain heads with
probability 1. I know that it is done through looping through the columns of
CoinTosses[,i], and need help cracking the code so to speak.

Please answer these questions before 10pm tonight, when I must make a final decision.

p.s.
The code I initially tried with before noticing the loop necesity was

CoinTosses20<-matrix(nrow=1000,ncol=2,data=
c(rbinom(n=1000, size=20, prob=.5),
rbinom(n=1000, size=20, prob=.6)))

for(i in 1:2){
CoinTosses20[,i]
}

#### Dason

You don't actually need a loop. It's probably easiest to get your head wrapped around the loop as opposed to the one liner I'm thinking of though. But I'm too tired to write out even any pseudo code at the moment.

#### bryangoodrich

##### Probably A Mammal
Use apply with second parameter equal to 2. It applies whatever function you define to each column. Thus, you apply it to your matrix that's going to hold the results of these simulations.

Code:
x <- matrix(NA, 5, 5)  # create an empty 5x5 matrix
apply(x, 2, function(z) sample(1:5, 5))
It results in

Code:
     [,1] [,2] [,3] [,4] [,5]
[1,]    4    5    4    5    1
[2,]    3    4    5    1    3
[3,]    2    2    2    3    5
[4,]    5    1    3    2    4
[5,]    1    3    1    4    2
Do you see why? Your problem isn't much more difficult than that, you just need to define your function, which you can do outside of the apply call, like

Code:
somefunction <- function(z) sample(1:5, 5)
apply(x, 2, somefunction)

?apply  # for more details

#### Rlanguagestatistictrainee

##### New Member
I have worked on and understand most of what bryangoodrich wrote.

Code:
somefunction <- function(z) sample(1:5, 5)
apply(x, 2, somefunction)
Code:
sample(x,y)
what would the x and y be designating respectively?
and how exactly does function(z) work or come into play?