Announcement

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

  • forvalues and xtile.

    Hello! I have a dataset with income and expense throughout several years (1992, 1994, ... 2016)
    I want to generate deciles. I know xtile doesn't work with by(). I tried using egen but it doesnt support weights and my data has weights. I thought i'd use forvalues however it doesn't seem to work either.

    My code is:

    forvalues i=1992(2)2016 {
    xtile decil=income [w=factor] if year==`i', nq(10)
    }

    The problem I find is that the code stops at 1992, that is that I have deciles for 1992 only.

    Can someone help me please?

  • #2
    did Stata provide an error message?

    at any rate, you are trying to produce only one new variable and that is what you got; if you want multiple new variables, you will need to modify what you did to name the new variable something different each time; if, instead, you just want one new variable but to replace some of the values each time thru the loop, then that calls for a different fix; please clarify what you want

    also, please provide a data example using -dataex- see the FAQ for instructions

    Comment


    • #3
      I think Rich Goldstein has hit the nail on the head in terms of identifying your problem.

      That said, if your data set is large, you can speed up the calculations by using a different approach:

      Code:
      capture program drop one_year
      program define one_year
          xtile decil = income [w = factor], nq(10)
          exit
      end
      
      runby one_year, by(year)
      -runby- is written by Robert Picard and me, and is available from SSC. It enables you to, in effect, use -by- with commands that do not allow the -by:- prefix by wrapping them inside a program. Note that, as with -by-, you do not need to create a new variable for each year, and you do not have to specify an -if- condition. The speedup in large data sets is quite appreciable.

      Comment

      Working...
      X