Announcement

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

  • A function for a number

    Hi, I am writing a loop that looks like this

    foreach code of numlist 1/202{
    forvalues i=1940/2020{
    forvalues j=0/4{
    summ y`i'q`j' if id==`code' & inlist(indicatorcode,"A", "B", "C", "D")
    replace y`i'q`j'=r(sum) in 2*`code'-406
    summ y`i'q`j' if id==`code' & inlist(indicatorcode,"X", "Y", "Z")
    replace y`i'q`j'=r(sum) in 2*`code'-405
    }
    }
    }

    There is a problem with the replace command as STATA can't understand 2*`code'-406 where it is written. How do I make this work?

    So essentially, when writing a command
    replace newvar = exp in #
    how can I make # into a function using a variable from foreach?

  • #2
    Here is one way to do it.

    Code:
    local first = 2 * `code'
    replace y`i'q`j'=r(sum) in `first'-406
    But the bigger deal here is that reshape long seems advisable.

    A small deal here is to use
    summarize, meanonly if all you want is the sum (despite the option name). https://journals.sagepub.com/doi/pdf...867X0700700311

    Comment


    • #3
      Try replacing 2*`code'-406, by
      Code:
      `=2*`code'-406'

      Comment


      • #4
        That said, consider these statements

        Code:
        replace y`i'q`j'=r(sum) in 2*`code'-406
        replace y`i'q`j'=r(sum) in 2*`code'-405
        The only different thing the first line does is replace ... in 406. Otherwise whatever you do in the first statement is overwritten by the second statement.

        Comment

        Working...
        X