When you're starting out, it's best to break things up into little pieces. So start with the first component of cost, $1.50 per pound of weight:
gen cost=1.5*weight
Next add the $0.25 per pound to ship for foreign cars:
replace cost=cost+.25*weight if foreign
And finally the $100 for cars with a rep78 of 5:
replace cost=cost+100 if rep78==5
Then the profit is price minus cost:
gen profit=price-cost
But once you're confident of what you're doing you can make it much more compact:
gen profit2=price-(1.5*weight + .25*weight*foreign + 100*(rep78==5))
This relies on two tricks: that true/false is equivalent to one/zero, and that adding something multiplied by zero is equivalent to not adding it. Thus .25*weight is only added for foreign cars, and 100 is only added for cars where rep78==5.
You can verify that these commands are equivalent with:
assert profit==profit2
Complete do file:
clear all
set more off
capture log close
log using data_ex1.log, replace
use auto
gen cost=1.5*weight
replace cost=cost+.25*weight if foreign
replace cost=cost+100 if rep78==5
gen profit=price-cost
gen profit2=price-(1.5*weight + .25*weight*foreign + 100*(rep78==5))
assert profit==profit2
list make profit*
log close
Last Revised: 12/17/2015