Announcement

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

  • Egen command in foreach loop

    Hi everyone,

    I am trying to find a more concise way to create 19 variables based on the following code:
    Code:
    egen total_saksinnhold_1 = total(saksinnhold_1), by(id_lnr)
    egen total_saksinnhold_2 = total(saksinnhold_2), by(id_lnr)
    egen total_saksinnhold_3 = total(saksinnhold_3), by(id_lnr)
    ​​​​​
    And so on up to #19. I tried the following foreach loop, but got an error message stating "invalid syntax":
    Code:
    foreach v of varlist saksinnhold* {
         egen total_`v’= total(`v’), by(id_lnr)
    }
    The data looks something like this:
    Code:
    input str10(id_lnr) byte(saksinnhold_1 saksinnhold_2 saksinnhold_3 saksinnhold_4 saksinnhold_5)
    "idlnr1" 0 1 0 0 0
    "idlnr1" 0 0 0 0 0
    "idlnr2" 1 0 0 0 0
    "idlnr2" 0 1 0 0 0
    "idlnr2" 0 0 0 0 0
    Could someone please recommend a correct for loop, or another way to create these new variables?

    Thank you!

  • #2
    egen total_saksinnhold_1 = total(saksinnhold_1), by(id_lnr)
    egen total_saksinnhold_2 = total(saksinnhold_2), by(id_lnr)
    egen total_saksinnhold_3 = total(saksinnhold_3), by(id_lnr)​​​​​
    Look at what is variable across the commands. A forvalues loop would work well here:


    Code:
    forval i=1/19{
        egen total_saksinnhold_`i' = total(saksinnhold_`i'), by(id_lnr)
    }

    foreach v of varlist saksinnhold* {
    egen total_`v’= total(`v’), by(id_lnr)
    }
    Your code in #1 should work provided that all variables with the prefix "saksinnhold" in the dataset are saksinnhold_1 - saksinnhold_19. So you may want to

    Code:
    set trace on
    to see where the code fails.
    Last edited by Andrew Musau; 19 Oct 2023, 04:28.

    Comment


    • #3
      The single quote characters need to look like

      Code:
       `v'
      not
      Code:
        
       `v’
      That is, the left single quotation mark is ASCII 96 and the right single quotation mark is ASCII 39.

      Code:
      . mata : uchar((96, 39))
             1   2
          +---------+
        1 |  `   '  |
          +---------+

      Comment


      • #4
        Thank you, Andrew Musau and Nick Cox! Those fixes worked. It seems like both the foreach loop that I originally wrote and the forval loop that Andrew suggested get the job done.

        Comment

        Working...
        X