我正在尝试提高我的函数编写技能,并对函数的正确结构有些困惑。我搜索了很多示例,但是我都不清楚。我的目标是在#RUN over and over
循环中运行for
部分,并构建一个函数,该函数使我可以控制循环的次数。
目前,我已经明白了这一点:
set.seed(123)
#Start but setting the conditions and being the Win Lose counters
Count_Win_Hunt=0
Count_Win_Moose=0
#RUN over and over
Hunter=1
Moose=7
win=0
while(win != 1){ a = sample(1:6,1) # dice roll
if( a<= 4) {Moose = Moose+a} else{Hunter = Hunter+a}
if( Hunter >= Moose ) { Count_Win_Hunt = Count_Win_Hunt +1 } else if( Moose >= 12) {Count_Win_Moose = Count_Win_Moose + 1}
if( Hunter >= Moose || Moose >= 12 ) {win = win+1} else {
#if not condition not meet roll again
a = sample(1:6,1) # dice roll
if( a<= 4) {Moose = Moose+a} else{ Hunter = Hunter+a}}}
# calculated the average win rates
paste0( round(Count_Win_Hunt/(Count_Win_Hunt+Count_Win_Moose),4)*100,"%"," of the time the Hunter won")
paste0( round(Count_Win_Moose/(Count_Win_Hunt+Count_Win_Moose)," of the time the Moose won")