Announcement

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

  • Creating a counter variable

    Hello,
    I have a dataset that is set up in the following way (and I apologize if the columns don't come out lined up in the post, but I saw this as one of the preferred ways that one could post snippets of a dataset):


    input ///
    obsnumber matched1 matched2
    1 4 7
    2 5 .
    3 4 1
    4 1 .
    5 2 6
    6 2 .
    7 4 .
    end

    In the dataset the variable "obsnumber" was created to be equal to its actual observation number (this is because I'm using the command "teffects nnmatch" in Stata 13.1, which provides the observation numbers of the individuals that each person gets matched to).

    What I'd like to do is create two new variables (such as "timesmatch1" and "timesmatch2") that would count the number of times that each "obsnumber" shows up in a column (i.e., got matched in the dataset) and then put that value in the row with that particular obsnumber (where timesmatch1 would be the counter for matched1 and so on). So for instance because the observation number "4" shows up three times in the "matched1" column, the value of timesmatch1 for obsnumber = 4 is then 3. The new dataset with the two new created variables would look like (and then in my actual dataset I have thousands of observations):

    input ///
    obsnumber matched1 matched2 timesmatch1 timesmatch2
    1 4 7 1 1
    2 5 . 2 0
    3 4 1 0 0
    4 1 . 3 0
    5 2 6 1 0
    6 2 . 0 1
    7 4 . 0 1
    end


    Could someone help me out with this one? So far I haven't had any luck through searching the Statalist archives (I've tried using levelsof, but couldn't get it to do what I wanted).

    Thanks for any help that could be provided,
    Tony

  • #2
    try -egen- with the "count" option; there are better ways to post; see the FAQ

    Comment


    • #3
      Hi Tony,

      see in the following link

      http://www.stata-journal.com/article...article=pr0029

      the codes are from there; and they are written by Nick

      Code:
      gen timesmatch1 = 0
      qui forval i = 1/`=_N' {
      count if obsnumber[`i'] == matched1
      replace timesmatch1 = r(N) in `i'
      }
      
      gen timesmatch2 = 0
      qui forval i = 1/`=_N' {
      count if obsnumber[`i'] == matched2
      replace timesmatch2 = r(N) in `i'
      }
      Last edited by Abraham Wolde-Tsadick; 14 Oct 2014, 15:17.

      Comment


      • #4
        Dear Abraham,
        Thank you!!!!! That code worked perfectly.
        Kind regards,
        Tony

        Comment

        Working...
        X