R语言:如何阻止replicate()执行play()时打印全部结果?
replicate() with Your Slot Machine Function Hey there! Let's figure out why your replicate(1000, play()) is spamming the console, while your dice roll code doesn't—spoiler: it's not about the typeof or class of the result vectors. Here's what's going on and how to fix it:
The Root Cause: Side Effects in Your play() Function
The issue is almost certainly that your play() function has console output built into it (like print(), cat(), or message() calls) that runs every time you execute it. These are called "side effects" because they do something beyond just returning a value.
For example, if your play() looks something like this:
play <- function() { # Your slot machine logic here... win_amount <- sample(c(0, 5, 20), 1, prob = c(0.9, 0.08, 0.02)) print(paste("You won", win_amount, "dollars!")) # This is the side effect return(win_amount) }
Every time play() runs (including each of the 1000 times in replicate()), that print() statement fires and sends text to the console. Your dice roll function, by contrast, probably only returns a value without any extra output—so replicate() just collects the results silently into roll.dice.
Data type (double vs integer) has nothing to do with this behavior. Test it yourself: a function that returns a double without side effects won't spam the console either:
double_test <- function() { runif(1) } test_vec <- replicate(1000, double_test())
No output here—just a vector stored in test_vec.
How to Fix It
You have a few options depending on whether you want to keep the output for single calls to play():
Remove the side effects entirely
If you don't needplay()to print anything when it runs, just delete anyprint(),cat(), or similar lines from the function. Thenreplicate()will run silently, andslot.machwill hold your 1000 results without console clutter.Add a verbose toggle for flexible behavior
If you want to see output when you callplay()alone but not during bulk runs, add a parameter to control the output:play <- function(verbose = TRUE) { # Your slot machine logic here... win_amount <- sample(c(0, 5, 20), 1, prob = c(0.9, 0.08, 0.02)) # Only print if verbose is TRUE if (verbose) { print(paste("You won", win_amount, "dollars!")) } return(win_amount) }Now, call
play()normally for single runs (with output), and useverbose=FALSEfor bulk replication:slot.mach <- replicate(1000, play(verbose = FALSE))This keeps the best of both worlds.
Suppress output temporarily (quick fix)
If you can't modifyplay()right now, you can wrap thereplicate()call incapture.output()to swallow all console output:slot.mach <- capture.output(replicate(1000, play()))Note: This will convert the output to a character vector, so you'll need to convert it back to numeric if you want to analyze the results:
slot.mach <- as.numeric(capture.output(replicate(1000, play())))This is a workaround though—fixing the function's side effects is the cleaner long-term solution.
内容的提问来源于stack exchange,提问作者JachymDvorak

