Announcement

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

  • forval within forval

    Dear all,

    I'm struggling to do the following:

    I have the following continuous variables:

    Month1Volume1
    Month1Volume2
    Month1Volume3
    Month2Volume1
    Month2Volume2
    ...
    Month74Volume3


    and I'm trying to do 2 things, change all missing data to zero and create a variable that represents the sum of all 5 volumes in a month. For that I tried the below code without success:

    forval i=1/74{
    forval j=1/5{
    replace Month`i'Volume`j'=0 if Month`i'Volume`j'=.
    }
    {

    forval i=1/74{
    generate Volume`i'=.
    forval j=1{
    replace Volume`i'=(Month`i'Volume`j') + (Month`i'Volume`=`j'+1')+ (Month`i'Volume`=`j'+1')
    }
    }


    Stata return invalid syntax for both attempts

    Could anyone help? I was recently introduced to forval and obviously missing something

    Sincerely

    Thyago

  • #2
    The replacement of missing values with zero requires no loops at all:
    Code:
    mvencode Month*Volume*, mv(0)
    That said, the cause of the syntax error is the use of = in your -if- clause. In Stata = refers to the operation of setting the value of what is on the left equal to the value of what is on the right. To specify that you want to test whether the thing on the left is equal to the thing on the right, you have to use ==.

    Your second issue is a bit confusing. You seem to have three Volume's for each month in your list of variables, and your attempt at using a forvlaues loop also suggests you have three, but you state that you have 5. Was that a typo? Anyway, on the assumption you have three, you can do it with just a single loop:

    Code:
    forvalues i = 1/74 {
        egen Volume`i' = rowtotal(Month`i'Volume*)
    }
    Note that for this code you don't have to specifically tell Stata how many volumes there are in any month: it will just add up however many you have.
    The reason your attempt gave you a syntax error is because you cannot say -forval j = 1{- Just having 1 alone is not a sufficient list of numbers for -forval-. If you want to have a "loop" that only iterates over the single number 1, you can write -forval j = 1/1 {-. But there aren't many situations where it would make sense to do that anyway.

    Comment


    • #3
      Thank you Clyde!

      Comment

      Working...
      X