Using function "cat" with "replicate" in R

1.4k views Asked by At

Is there a way how to combine function "cat" with function "replicate" in R?

I want to see number of "loops" R has already made at a particular moment. However, instead of using "for" loop, I prefer to use "replicate". See the simple example below:

 Data <- rnorm(20,20,3)

 # with for loop
 N <- 1000
 outcome <- NULL

 for(i in 1:N){
      Data.boot <- sample(Data, replace=TRUE)
      outcome[i] <- mean(Data.boot)
      cat("\r", i, "of", N)
 }

  #the same but with replicate 
  f <- function() {
  Data.boot <- sample(Data, replace=TRUE)
  outcome <- mean(Data.boot)
  return(outcome)
  }
  replicate(N, f())

Thus, any ideas how to implement function "cat" with "replicate" (as well as other approaches to see a number of how many times the function of interest has been executed with "replicate") would be very appreciated. Thank you!

2

There are 2 answers

0
Nick Kennedy On BEST ANSWER

As an alternative, you could use sapply instead of replicate:

Data <- rnorm(20,20,3)
N <- 1000

f <- function(i) {
  Data.boot <- sample(Data, replace=TRUE)
  cat("\r", i, "of", N)
  mean(Data.boot)
}
outcome <- sapply(1:N, f)

or alternatively, using plyr, you could use raply with the progress option (if your main purpose is to see how far through you are):

outcome <- plyr::raply(N, mean(sample(Data, replace = TRUE)), .progress = "text")
0
Eric Brooks On

You could use scoping in the following way:

  i = 0

  f <- function() {
   Data.boot <- sample(Data, replace=TRUE)
   outcome <- mean(Data.boot)

   i <<- i + 1  
   print(i)
   return(outcome)
  }