I'm trying to create a function in R to simulate the experiment of tossing four coins as many times as m times, each experiment records the appearance of "numbers" or "images" on each coin.
Present the results of m experiments in tabular form, and add the "number of sides of the number that appears" in the last column of the table.
Sim_Coin<-function(m){
c1<-c()
c2<-c()
cs<-c()
for(i in 1:m)
{
c1<-rbind(d1,sample(0:1,size=1)
c2<-rbind(d2,sample(0:1,size=1)
}
cs<-c1+c2
v<-cbind(c1,c2,cs)
v<-as.data.frame(v)
names(v)<-c("coin1","coin2","sum")
return(v)
}
But it fails and I don't know how to create the table
R is a vectorized language so in many cases the need for a loop can be avoided. So instead of looping m times, just pick m samples from 0 or 1. This will greatly improve performance.
Also progressively adding onto a vector or data frame with bind function, inside a loop, is slow in R since a new copy of the information is created with each function call.
Take a look at this streamline code:
Sim_Coin<-function(m){
coin1<-sample(c("head", "tail"), size=m, replace=TRUE)
coin2<-sample(c("head", "tail"), size=m, replace=TRUE)
v<-data.frame(coin1, coin2)
v$sum <- apply(v, 1, function(i){sum(i=="head")})
return(v)
}
Sim_Coin(3)
coin1 coin2 sum
1 tail tail 0
2 head head 2
3 tail head 1
Since your question talked about flipping 4 coins and not just 2, here is an expanded version:
Sim_Coin2<-function(m){
n<-4. #number of coins to flip
#create n vectors m long
coins<- lapply(1:n, function(i) {
sample(0:1, size=m, replace=TRUE)
})
#make data frame and rename columns
dfcoin<-as.data.frame(do.call(cbind, coins))
names(dfcoin)<-paste0("Coin", 1:n)
#calculate the number of heads by taking the sum of the rows
dfcoin$sum <- rowSums(dfcoin)
dfcoin
}
Sim_Coin2(10)