Announcement

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

  • Randomly selecting from a list of values

    I would like to make two lists, list1=["A","B"] and list2=[2008, 2009] and randomly select 1000 combinations from these 2 lists (e.g., ("A",2008), ("A",2009), ("B",2009),...). Then for each of these combinations I would like to run a two-step loop in my dataset (using `i'="A" and `j'=2008 in one iteration for example).
    Last edited by Hossein Jebeli; 02 Jun 2023, 06:24.

  • #2
    The syntax you give is not Stata syntax but that is not crucial. What is crucial is the bit you don't tell us about what else you want to do and what other data you have. Whether it's a good idea to create a dataset with 1000 observations or a better idea to write a loop over 1000 instances depends on all that.

    Also, you don't spell it out, but a guess is that A and B and also 2008 and 2009 occur with equal probability.

    Comment


    • #3
      Sorry if it was not clear. I would like to loop over these 1000 instances (i.e., your second suggestion), so would be great to make lists instead of making new datasets.

      And yes, with equal probability.

      Comment


      • #4
        I share Nick's uncertainty about what you want. I'm assuming by "list" you mean "local macro," but creating such macros is not needed to obtain combinations as you request. (Doing that would be useful if your "lists" had more than a few items.) Also, I don't know what you have in mind by a "two-step loop," so I'll leave that aside. With those caveats, the following shows some relevant technique:

        Code:
        forval r = 1/1000 {
           local i = cond(runiform() > 0.5, "A", "B")
           local j = cond(runiform() > 0.5, "2008", "2009")
           di "rep `r': `i' `j'"
        }

        Comment


        • #5
          Thanks Mike! This is exactly what I was looking for. Is there a way to do this with more than 2 elements? I have 6 values for i (i.e., "A", "B", "C",...) and 60 values for j (i.e., 200801, 200802,...).
          Last edited by Hossein Jebeli; 02 Jun 2023, 10:08.

          Comment


          • #6
            Yes, there are ways to do that. I wish you had asked for that originally.
            Code:
            local choices1 = "A B C D E F"
            // Easier than typing out by hand
            local choices2 = ""
            forval i = 1/60 {
               local next = 200800 + `i'
               local choices2 "`choices2' `next'"
            }
            forval r = 1/1000 {
               local i = word("`choices1'", runiformint(1, 6))
               local j = word("`choices2'", runiformint(1, 60))
            }

            Comment

            Working...
            X