我正在努力提高我的函数编写技能,但我对函数的正确结构感到有点困惑。我已经搜索了大量的例子,但没有一个对我来说是那么清楚。我的目标是在一个for循环中运行#RUN over and over部分,并构建一个函数来控制我可以循环它的次数。
目前,我已经谈到了这一点:
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),4)*100,"%"," of the time the Moose won")发布于 2019-11-07 20:56:26
除了我对你的问题的一般性问题(请更具体地说明你的实际问题),你的for-循环有一个错误的语法。它们应该是这样的:
for (val in sequence)
{
statement
}所以应用到你的函数中,它们应该是这样的:
for (val in c(1:4))
{
probability + (hunter,goose+val,num+1)
}
for (val in c(5:6))
{
probability + (hunter,goose+val,num+1)
print probability
}然而,它们不仅在句法上是错误的,而且它们的内容似乎也是错误的。
例如,在你的第二个for循环中,鹅向前走了一步,尽管它应该是猎人。另外,这不是两个for-循环,而应该是一个if语句,如下所示:
if (val <= 4) {
probability + (hunter,goose+val,num+1)
}
else {
probability + (hunter+val,goose,num+1)
}最后,您的函数的整个结构看起来很奇怪(并且具有误导性的命名变量)。它不应该是这样的吗:
dice_roll <- function(hunter,goose, win){
# While to check for winning condition
while(win != 1){
dice_roll = sample(1:6, 1) # simulate dice roll
# If statement depending on dice roll, increasing value of hunter or goose by dice roll
# Change win condition
If(hunter >= goose){
win <- 1
}
}
dice_roll(1,7,0)https://stackoverflow.com/questions/58748899
复制相似问题