Announcement

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

  • Loop over Observations from a specific Variable

    Dear All,

    Using STATA 13 I struggle with the following problem.

    I want to construct a loop based on observations from one specific string variable (in my case retailer). Specifically, I need the following loop:


    forvalue i in CO DL EV EV NW {

    gen Sold_Product_`i' =.


    Yet, I do not want the varlist (CO DL EV EV NW) to be fixed. I have this data in a variable but don't know how to transform it into a list. Also, some of the retailers are duplicates in my variable.

    My data looks like this:


    input str2(retailer) byte(product_id retailer_id)

    "CO" 11 1
    "CO" 6 1
    "CO" 16 1
    "DL" 9 2
    "DL" 1 2
    "DL" 17 2
    "DL" 11 2
    "DL" 4 2
    "EV" 15 3
    "EV" 7 3
    "EV" 11 3
    "NW" 13 4
    "NW" 2 4
    "NW" 17 4
    "NW" 1 4

    end


    Many thanks in advance.

    Best,
    Markus

  • #2
    Code:
    levelsof retailer, local(retailers)
    
    foreach r of local retailers {
        gen Sold_Product_`r' = .
    }
    One caution: you are using the values in the variable retailer as part of a new variable name. If the values in retailer have embedded blanks or any special characters, then Stata will complain that you are trying to create an illegal variable name and will abort the loop. So you should first check that all of the values of retailer would be legal as part of a variable name. (Nick Cox's -charlist-, available from SSC is helpful in this regard.) If there are some values that do not meet these requirements, take a look at the -strtoname()- command. The other issue you might encounter is if some of the values of retailer are long enough that "Sold_Product_`r'" would contain more than 32 characters. Some kind of abbreviation would then be needed.

    Comment


    • #3
      Dear Clyde,

      many thank for your instant help again.

      Best
      Markus

      Comment

      Working...
      X