Search code examples
stata

One variable in kg and grams. another indicates which unit; how can I get new variable in kg?


In Stata quantity has inputs in both kg and grams. while unit =1 indicates kg and unit=2 indicates grams. How can I generate a new variable quantity_kg which converts all gram values into kg?

My existing dataset-

clear
input double(hhid quantity unit unit_price)
  1   24 1   .
  1    4 1   .
  1  350 2  50
  1  550 2  90
  1    2 1  65
  1  3.5 1  85
  1    1 1  20
  1    4 1  25
  1    2 1   .
  2    1 1  30
  2    2 1  15
  2    1 1  20
  2  250 2  10
  2    2 1  20
  2  400 2  10
  2  100 2  60
  2    1 1  20

My expected dataset

input double(hhid quantity unit unit_price quantity_kg)
  1   24 1   .  24
  1    4 1   .  4
  1  350 2  50 .35
  1  550 2  90 .55
  1    2 1  65  2
  1  3.5 1  85  3.5
  1    1 1  20  1
  1    4 1  25  4
  1    2 1   .  2
  2    1 1  30  1
  2    2 1  15  2
  2    1 1  20  1
  2  250 2  10 .25
  2    2 1  20  2
  2  400 2  10 .40
  2  100 2  60 .10
  2    1 1  20 1


Solution

  • // unit 1 means kg, unit 2 means g, and 1000 g = 1 kg
    generate quantity_kg = cond(unit == 1, quantity, cond(unit == 2, quantity/1000, .)) 
    

    Your example doesn't have any missing values on unit, but it does no harm to imagine that they might occur.

    Providing a comment by way of explanation could be anywhere between redundant and essential for third parties.