1

I'm having trouble with storing the output of a function into a variable. I think it's best that I give some context to the problem I'm trying to work out. Suppose that players "a" and "r" play a game of tennis, the runningScoreFn sums the pointHistory vector and puts everything together in a nice data.frame

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

The oneEpxiermentGameFn that plays out a game of "a" v.s "r".The first player to win 4 points wins the game, but he must be ahead by at least 2 points. "r" has 60% chance of winning a point.

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 shows the probability that Roger wins the game.

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

ok=oneExperimentGameFn(pRogerPoint)
})}

Here I wish to store the output into the variable ok, but ok returns NULL. I think this has something to do with my oneExperimentGameFn. I also tried ok = RogerGameFn, but ok also returns NULL.

4

1 回答 1

2

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

如果您只是想捕获打印语句,您可以使用capture.output(.)

 ok <- capture.output(oneExperimentGameFn(pRogerPoint))
于 2013-04-21T00:12:25.630 回答