简体   繁体   中英

Using function "cat" with "replicate" in R

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!

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)
  }

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM