将函数的输出存储到R中的变量中

时间:2013-04-20 23:28:19

标签: r while-loop average mean

我将函数的输出存储到变量中时遇到问题。我认为我最好能够解决我正在努力解决的问题。 假设玩家“a”和“r”玩网球游戏,runningScoreFn会将pointHistory向量相加,并将所有内容放在一个不错的数据中。框架

runningScoreFn = function(pointHistory){
playerUni = c("a", "r")
cols = sapply(playerUni, function(thisPlayer){
cumsum(pointHistory == thisPlayer)
})
names(cols) = playerUni
cbind(pointHistory, as.data.frame(cols))
}

oneEpxiermentGameFn发挥“a”v.s“r”游戏。第一位赢得4分的玩家赢得了比赛,但他必须领先至少2分。 “r”有60%的几率赢得一分。

pRogerPoint = 0.6

oneExperimentGameFn = function(pRogerPoint){
game = c(rep("r",pRogerPoint * 100), rep("a", 100-pRogerPoint*100))
i = 4
keepGoing = TRUE
while(keepGoing){
whosePoint = sample(game, size=i, replace=TRUE)
if(sum(whosePoint=="r")-sum(whosePoint=="a")>=2){
success = TRUE
print(cbind(runningScoreFn(whosePoint),success=success))
keepGoing = FALSE
}else if(sum(whosePoint=="a")-sum(whosePoint=="r")>=2){
success = FALSE
print(cbind(runningScoreFn(whosePoint),success=success))
keepGoing = FALSE
}
i=i+1
}
}

pRogerGameFn显示罗杰赢得比赛的概率。

pRogerGameFn = function(pRogerPoint, NExperiments){
RogerGameFn = lapply(1:NExperiments,function(dummy){

ok=oneExperimentGameFn(pRogerPoint)
})}

这里我希望将输出存储到变量ok中,但ok返回NULL。我认为这与我的oneExperimentGameFn有关。 我也试过ok = RogerGameFn,但ok也返回NULL。

1 个答案:

答案 0 :(得分:1)

函数oneExperimentGameFn没有返回任何内容。 如果要返回特定值,请在函数末尾插入return(.)命令(或其他适当的位置)。

如果您只想捕获打印报表,可以使用capture.output(.)

 ok <- capture.output(oneExperimentGameFn(pRogerPoint))