Announcement

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

  • Looping - Creating new variables

    Dear all,

    Suppose I have the following dataset.

    Code:
    input    var1    var2    var3    var4
    12    2    3    12
    4    5    6    24
    23    65    9    54
    21    7    12    512
    2    8    16    12
    6    10    10    12
    end
    I'd like to create new variables by dividing each variable (var1, var2, and var3) by a corresponding value of the variable var4.

    More specifically, I'd like to create var5 by dividing var1 by the first observation of var4 (in this case, 12), var6 by dividing var2 by the second observation of var4 (24) and var7 by dividing var3 by the third observation of var4 (54).

    Could anyone please help me with this ?

    Thank you very much for your help,

    Vinh

  • #2
    Perhaps this code will start you in a useful direction.
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(var1 var2 var3 var4)
    12  2  3  12
     4  5  6  24
    23 65  9  54
    21  7 12 512
     2  8 16  12
     6 10 10  12
    end
    forvalues i=1/3 {
        local j = `i' + 4
        generate var`j' = var`i'/var4[`i']
        }
    format var5-var7 %9.3f
    list, clean noobs
    Code:
    . list, clean noobs
    
        var1   var2   var3   var4    var5    var6    var7  
          12      2      3     12   1.000   0.083   0.056  
           4      5      6     24   0.333   0.208   0.111  
          23     65      9     54   1.917   2.708   0.167  
          21      7     12    512   1.750   0.292   0.222  
           2      8     16     12   0.167   0.333   0.296  
           6     10     10     12   0.500   0.417   0.185

    Comment


    • #3
      Hi William,

      That is very helpful.

      Many thanks,

      Vinh

      Comment


      • #4
        Dear William Lisowski,

        You loop codes are really clever, however, could you please explain a bit about meanings of your codes? Say, at the 2nd code line, why do we need to put " + 4" and what is the meaning of adding

        [`i'] right behind var4 at the 3rd code line? Thank you. DL

        Comment


        • #5
          These are the commands that the loop creates and runs.
          Code:
              generate var5 = var1/var4[1]
              generate var6 = var2/var4[2]
              generate var7 = var3/var4[3]
          We see that in the first command, i = 1 so j = 5 and var`i' becomes var1 and var`j' becomes var5 and var4[`i'] becomes var4[1] which is the value of var4 in observation 1.

          Comment


          • #6
            William Lisowski, thank you so much for your detail explanations. I now understand how the loop commands work in this case.

            Best regards,

            DL

            Comment

            Working...
            X