Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Store a value in a loop

    Hello everybody, I am new here and I am learning stata so I apologize in advange for the very trivial question.

    I need to run 10000 loop to simulate a value, ho am i supposed to store the value obtained in each loop?

    example:

    set obs 50
    gen RVuniforme = runiform()
    gen myvalue=.
    summarize RVuniforme
    scalar myvalue = r(mean)

    How am I supposed now to store only one value of the variable myvalue and start over the process again and again until I reach the 10000th simulation?

    Thank you


  • #2
    You don't need a loop here and even if you used one you would still have the problem you're realising, how to store 10000 results. I would turn the problem around.

    Code:
    clear
    set obs 500000
    set seed 314159
    gen group = ceil(_n/50)
    gen RVuniforme = runiform()
    bysort group: egen double wanted = mean(RVuniforme)
    egen tag = tag(group)
    qnorm wanted if tag, xla(.34(.04).66) yla(.34(.04).66)
    What bit me on my first draft was forgetting that there are only 10000 distinct values, not 50000, Hence the tagging.

    You should naturally use a seed of your choice and you may need slightly different axis labels.

    You read the help on anything unfamiliar,

    Code:
    help ceil()
    help egen
    help qnorm
    Detail: You do nothing with the myvalue variable you create.

    Comment


    • #3
      Thank you, Nick. That was very helpful, and it worked perfectly.
      I have a minor question: You essentially use a single column with a length of n x k, where n is the number of observations (50) and k is the number of simulations (10,000). How would I handle this if n and k increase significantly? For instance, if I needed to run a loop with one million iterations on a dataset with 10,000 observations, this would result in an enormous size (10 billion entries). Is there any way to optimize or shortcut this process?

      Thank you again for your help—I really appreciate it!

      Comment


      • #4
        It depends what you want to do. If I wanted a million scalar results, I might reach for postfile or I might extend the dataset to 1 million and loop over iterations using the first 10,000 observations as data. Or I might check out frames. I agree that 10 billion observations is impractical.

        Comment

        Working...
        X