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

  • Foreach loop across variables

    I have over a thousand dummy variables for 30,000 data entries. I want to find a way to count the number of times each one of those variables appears as 1 using a foreach 'variable' loop command. Would be helpful if there was another command. Here is the command I used:

    After generating a new variable "fortier" to count the number of times a variable appears as '1', I then tried to replace it with a loop in the following way, where Stern and Pierneef are 2 out of the 1000 dummy variables.

    foreach `var' of varlist Stern Pierneef {
    replace fortier = count(`var') if `var'==1

  • #2
    Since we are in the Mata forum a quick way is:
    . clear
    . set rmsg on
    r; t=0.00 8:17:53
    . mata: // create dataset
    ------------------------------------------------- mata (type end to exit) ---------------
    :     N = 30000
    :     V = 1000
    :     names = "v" :+ strofreal(1..V)
    :     values = runiformint(N, V, 0, 1)
    :     nhb_sae_addvars(names, values) // Install by ssc install matrixtools
    : end
    r; t=64.84 8:18:58
    . mata: //add a variable with rowtotals/rowcounts
    ------------------------------------------------- mata (type end to exit) ---------------
    :     rowcounts = rowsum(st_data(.,.))
    :     nhb_sae_addvars("rowcounts", rowcounts)
    : end
    r; t=0.33 8:18:59
    end of do-file
    r; t=0.00 8:18:59
    • I use my own Mata function nhb_sae_addvars() to insert variables and values into Stata
    • The only thing You really need is line in red
    Kind regards



    • #3
      Meanwhile #1 is a little confused about local macros. Further, count() is an egen function, only.

      But something like this should be closer to what you want. Naturally, your varlist will differ.

      scalar sum = 0
      foreach var of var Stern Pierneef {
          su `var', meanonly
          scalar sum = sum + r(sum)
      where it is understood that an indicator variable is 0 or 1 or just possibly missing, so that the sum is identical to the number of 1s present.