我是R的新手,我有一个小问题。我在R中的老虎机上有以下代码(来自" R&#34的实践编程;来自Garrett Grolemund。
当我在下面看到的老虎机上使用play()函数时,我得到一个数字,告诉我我赢了多少。当我使用以下代码复制结果时:
slot.mach <- replicate(1000,play())
R在我的控制台中打印所有1000个示例。我不明白的是,当我在我的骰子上使用相同的复制功能时,也会有一个数字作为结果,它不会打印所有的卷,而只是将它们作为矢量添加到我的对象我可以马上使用qplot(这也是我想要的老虎机)。
我显然不希望所有这些都打印出来,因为它花费了大量的时间和时间。空间并没有必要让我看到所有结果。
我的猜测是它可能与对象的类和类型有关,见下文:
[1] "integer"
> typeof(slot.mach)
[1] "double"
> class(slot.mach)
[1] "numeric"
> typeof(roll.dice)
[1] "integer"
> class(roll.dice)
[1] "integer"
我不知道帮助我是否很重要,但这是我的老虎机的全部代码:
score <- function(symbols) {
#identify case of symbols frequency
same <- length(unique(symbols)) == 1
bars <- symbols %in% c("B","BB","BBB")
#get prize
if (same) {
payouts <- c("DD" = 100,"7" = 80, "BBB" = 40, "BB" = 25, "B" = 10, "C" = 10,
"0" = 0)
prize <- unname(payouts[symbols[1]])
} else if (all(bars)){
prize <- 5
} else {
cherries <- sum(symbols == "C")
prize <- c(0,2,5)[cherries+1]
}
#adjust for diamonds
diamonds <- sum(symbols == "DD")
prize <- prize*(2^diamonds)
}
然后我可以发挥这个功能:
play <- function() {
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))
symbols <- get_symbols()
print(score(symbols))
}
最后,我得到了一个打印结果,所以每个&#34; play()&#34;给了我一个号码。通常它为零,有时它只是一小部分(你可以看到上面的概率)。
这是我的骰子功能
roll.dice <- function(){x <- 1:6
y <- c(1/8,1/8,1/8,1/8,1/8,3/8)
dice<-sample(x,size=2,replace=TRUE,prob=y)
sum(dice)}
roll.dice <- replicate(10000,roll.dice())
答案 0 :(得分:1)
replicate
print
因为您replicate
正在调用print
将print
来电更改为返回,您将在您指定的replicate
返回值的对象中获得一系列分数。
在get_symbols
的定义周围添加一个假定的缺失右括号,你得到:
play <- function() {
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))
}
symbols <- get_symbols()
score(symbols)
}
使用您编写的其他函数运行它,当您调用:roll.dice <- replicate(10000,roll.dice())
时,您将获得一个长度为10000的整数向量,其中包含10000个骰子角色的结果,没有任何内容打印到控制台。
答案 1 :(得分:0)
就像@DanHall所说,你不想print
你的结果。我已将您的功能修改为您要查找的内容。简单来说,函数非常有用,因为我们只需要定义一次,我们可以以更具视觉吸引力的方式调用它们。每次运行get_symbols
时都会定义play
函数,这是不必要的。您希望代码看起来像,
score <- function(symbols) {
#identify case of symbols frequency
same <- length(unique(symbols)) == 1
bars <- symbols %in% c("B","BB","BBB")
#get prize
if (same) {
payouts <- c("DD" = 100,"7" = 80, "BBB" = 40, "BB" = 25, "B" = 10, "C" = 10,
"0" = 0)
prize <- unname(payouts[symbols[1]])
} else if (all(bars)){
prize <- 5
} else {
cherries <- sum(symbols == "C")
prize <- c(0,2,5)[cherries+1]
}
#adjust for diamonds
diamonds <- sum(symbols == "DD")
prize <- prize*(2^diamonds)
prize
}
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))
}
play <- function() {
symbols <- get_symbols()
score(symbols)
}