Announcement

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

  • Help - Countif function?

    Hi everyone,

    I am new to this forum and Stata. I wonder if there is a trick/command which performs similar to the COUNTIF function in excel?

    I tried to looked up on the help file and internet but without luck. My purpose is to count the share of foreigners to the total population each year (30 years time series).

    "
    gen nationality = 1 if nation = 1
    replace nationality = 0 if inrange(nation,121,997) /*values between 121 to 997 are the nationalities of the foreigners*/
    replace nationality = . if nation = 998 /*unknown nationality*/

    label variable nationality "Nationality"

    label define nationality 1 "Natives" 0 "Immigrants"
    "

    Would be grateful if any of you could give me a hint.

    Thanks a lot.

  • #2
    Welcome to the Stata Forum/Statalist.

    Please read the FAQ, particularly on how to share data and command when posting in this Forum.

    You may prefer to share data under CODE delimiters or by installing the SSC dataex.

    That said, I wonder whether - count - + "by" as seen here in the Manual would'nt fit your needs.
    Best regards,

    Marcos

    Comment


    • #3


      Code:
      gen native = nation == 1 if nation != 998
      will map nation == 1 to 1, 998 to missing and other non-missing values to 0.

      Then

      Code:
      bysort year : egen pc_native = mean(100 * native)
      
      by year: egen pc_foreign = mean(100 * (1 -native))
      
      tabdisp year, cell(pc_foreign)
      are ways to get % native and % foreign, followed by a token tabulation command.

      The missings will be ignored. If you want proportions or fractions, then naturally omit multiplication by 100.

      (Code in #1 will not work whenever the syntax requires == and = is typed.)

      Comment


      • #4
        Hi Nick,
        Thank you so much for your help and advise. I also found something similar to your suggestion. It works!

        Comment

        Working...
        X