1

I'd like to make a data frame using only the last computed values from a Repeat loop. For the repeat and sample functions, I'm using this data. The numbers in Prob column are the probabilities of each number to occur. enter image description here

b <- 1
repeat {
  c <- sample(a$Plus, size=1, prob=(a$Prob))
  cat(b, '\t', c, '\n')
  b <- b + 1
  if (c >= 10) {
    {
      break
    }
  }
}
#I'm interested in the result greater than 10 only

If I run the code above, then it will compute something like

1    4 
2    8
3    13 

If I run this again, it will compute different results like..

1    9 
2    3
3    7
4    3
5    11

What I'd like to do is to make a data frame using only the last outputs of each loop. For example, using the computed data above, I'd like to make a frame that looks like

Trial Result
3 13
5 11

Is there any way to repeat this loop the number of times I want to and make a data frame using only the last outputs of each repeated function?

jay.sf
  • 60,139
  • 8
  • 53
  • 110

1 Answers1

1

You can use a user defined function to do this. Since you haven't given your dataframe a, I've defined it as follows:

library(tidyverse)

a <- tibble(
  Plus = 1:15,
  Prob = seq(from = 15, to = 1, by = -1)
)

The following function does the same thing as your repeat loop, but stores the relevant results in a tibble. I've left your variable b out of this because as far as I can see, it doesn't contribute to your desired output.

samplefun <- function(a) {
  c <- sample(a$Plus, size=length(a$Plus), prob=a$Prob)
  
  res <- tibble(
    Trial = which(c >= 10)[1],
    Result = c[which(c >= 10)[1]]
  )
  
  return(res)
}

Then use map_dfr to return as many samples as you like:

nsamples <- 5
map_dfr(1:nsamples, ~ samplefun(a))

Output:

# A tibble: 5 x 2
  Trial Result
  <int>  <int>
1     4     11
2     6     14
3     5     11
4     2     10
5     4     15
Rory S
  • 1,278
  • 5
  • 17
  • Thank you very much for answering my question. I'm embarrassed to say this, but it has been my curiosity for many years, and you solved it.. You made my day. Thank you! – LoveRsomuch Jul 03 '21 at 22:38
  • @LoveRsomuch that's okay! Really glad you found it useful :) – Rory S Jul 04 '21 at 06:50
  • Thank you for your kindness. Can I ask you another question? This R function is really fun and so interesting that it gave me another curiosity. I would be really grateful if you could look at this post: https://stackoverflow.com/questions/68248184/can-i-make-a-function-that-makes-a-dataframe-like-this-using-loops-follow-up-q – LoveRsomuch Jul 04 '21 at 19:35
  • @LoveRsomuch sure - I've posted an answer and a comment on that one. – Rory S Jul 05 '21 at 08:04