expand.grid函数可以方便快捷地写出n个向量元素的所有组合。
die<-c(1,2,3,4,5,6)
rolls<-expand.grid(die,die)
rolls$value<-rolls$Var1+rolls$Var2
head(rolls,3)
prob<-c("1"=1/8,"2"=1/8,"3"=1/8,"4"=1/8,"5"=1/8,"6"=3/8)
prob[rolls$Var1]
rolls$prob1<-prob[rolls$Var1]
rolls$prob2<-prob[rolls$Var2]
rolls$prob<-rolls$prob1*rolls$prob2
sum(rolls$value*rolls$prob)
for循环不会返回输出结果,想返回结果,需用print语句。
完整的老虎机求平均返还率程序:
wheel<-c("DD","7","BBB","BB","B","C","0")
rolls<-expand.grid(wheel,wheel,wheel,stringsAsFactors = FALSE)
get_symbols<-function(){
wheel<-c("DD","7","BBB","BB","B","C","0")
sample(wheel,size=3,replace=TRUE,prob=c(0.03,0.03,0.06,0.1,0.25,0.01,0.52))
}
prob<-c("DD"=0.03,"7"=0.03,"BBB"=0.06,"BB"=0.1,"B"=0.25,"C"=0.01,"0"=0.52)
rolls$prob1<-prob[rolls$Var1]
rolls$prob2<-prob[rolls$Var2]
rolls$prob3<-prob[rolls$Var3]
rolls$prob<-rolls$prob1 * rolls$prob2 * rolls$prob3
sum(rolls$prob)
rolls$price<-NA
for(i in 1:nrow(rolls)){
symbols<-c(rolls[i,1],rolls[i,2],rolls[i,3])
rolls$price[i]<-score(symbols)
}
sum(rolls$prob*rolls$price)