Search
   >> Home >> Resources & support >> FAQs >> Setting different observations equal

How can I replace an observation of a variable with a different observation for another variable?

Title   Setting different observations equal
Author Jeremy B. Wernow, StataCorp
Date June 2000; minor revisions September 2005

Here is a common mistake that is made when attempting to replace an observation of a variable with a different observation from another variable:

 . list

      +--------------+
      |  price   mpg |
      |--------------|
   1. |  4,099    22 |
   2. |  4,749    17 |
   3. |  3,799    22 |
   4. |  4,816    20 |
   5. |  7,827    15 |
      |--------------|
   6. |  5,788    18 |
   7. |  4,453    26 |
   8. |  5,189    20 |
   9. | 10,372    16 |
  10. |  4,082    19 |
      +--------------+

 . replace mpg[4] = price[7]
 weights not allowed
 r(101);

The correct syntax would be to use the in qualifier.

 . replace mpg= price[7] in 4
 (1 real change made)
      
 . list

      +---------------+
      |  price    mpg |
      |---------------|
   1. |  4,099     22 |
   2. |  4,749     17 |
   3. |  3,799     22 |
   4. |  4,816   4453 |
   5. |  7,827     15 |
      |---------------|
   6. |  5,788     18 |
   7. |  4,453     26 |
   8. |  5,189     20 |
   9. | 10,372     16 |
  10. |  4,082     19 |
      +---------------+

In programming, you might use macros in place of known values. Observe how the following do-file performs the same task as the above example:

 ------------------------------------------------------example.do
 local x = 7
 local i = 4
 replace mpg = price[`x'] in `i'
 ------------------------------------------------------example.do

 . list

      +--------------+
      |  price   mpg |
      |--------------|
   1. |  4,099    22 |
   2. |  4,749    17 |
   3. |  3,799    22 |
   4. |  4,816    20 |
   5. |  7,827    15 |
      |--------------|
   6. |  5,788    18 |
   7. |  4,453    26 |
   8. |  5,189    20 |
   9. | 10,372    16 |
  10. |  4,082    19 |
      +--------------+

 . do example.do

 . local x = 7

 . local i = 4

 . replace mpg = price[`x'] in `i'
 (1 real change made)

 . 
 end of do-file

 . list

      +---------------+
      |  price    mpg |
      |---------------|
   1. |  4,099     22 |
   2. |  4,749     17 |
   3. |  3,799     22 |
   4. |  4,816   4453 |
   5. |  7,827     15 |
      |---------------|
   6. |  5,788     18 |
   7. |  4,453     26 |
   8. |  5,189     20 |
   9. | 10,372     16 |
  10. |  4,082     19 |
      +---------------+
The Stata Blog: Not Elsewhere Classified Find us on Facebook Follow us on Twitter LinkedIn Google+ Watch us on YouTube