【发布时间】:2021-09-30 21:29:43
【问题描述】:
rc<-1 # the number of red balls
wc<-1 # the number of white balls
red<-rep("Red",rc)
white<-rep("White",wc)
jar<-c(red,white)
nb<-5 ### number of draws
N=10 # Number of experiments
new_data<-matrix(NA,nrow = N,ncol = nb+1)
count_red_new<-matrix(NA,nrow = N,ncol = nb)
red_count<-rep(NA,N)
#### nested loop
for(i in 1:N){
for(j in 1:nb){
new_data[i,j]<-sample(jar,1,replace = T)
if(new_data[i,j]=="Red"){
count_red_new[i,j]=1
}else{
count_red_new[i,j]=0
}
red_count[i]=sum(count_red_new[i,])
new_data[i,nb+1]=red_count[i]
}
}
colnames(new_data)<-c("Draw1","Draw2","Draw3","Draw4","Draw5","Red Ball Count")
new_data<-data.frame(new_data)
#new_data$Red.Ball.Count<-as.integer(new_data$Red.Ball.Count)
new_data
上面的代码用于运行一个关于在 5 次平局中拉红球和白球的实验。这个实验进行了 10 次迭代。如上所述,我在两者之间使用了嵌套循环。如何使用 purrr 进行嵌套循环,以便将输出存储在矩阵或数据框中?
【问题讨论】:
标签: r nested-loops purrr