如何创建抛硬币R的功能

How to create function of tossing coin R

我正在尝试在 R 中创建一个函数来模拟投掷四枚硬币 m 次的实验,每个实验记录每个硬币上 "numbers" 或 "images" 的出现.
以表格形式呈现m次实验的结果,并在table的最后一栏加上"number of sides of the number that appears"。

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)
}

但是它失败了,我不知道如何创建 table

R 是一种矢量化语言,因此在许多情况下可以避免循环的需要。因此,与其循环 m 次,不如从 0 或 1 中选取 m 个样本。这将大大提高性能。

在循环中使用绑定函数逐步添加到向量或数据帧上,在 R 中速度很慢,因为每次函数调用都会创建一个新的信息副本。

看看这段精简代码:

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

由于您的问题涉及抛 4 个硬币而不是 2 个,这里是一个扩展版本:

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)