Hello,
I don't have a data problem in particular. I'm trying to learn about how Stata works and I find myself a bit puzzled by the if command. I get there's a difference between the if command and an if qualifier, but it's hard for me to understand the difference between :
1) a series of -if- commands
2) an if command, then a series of -else if- commands until the end,
3) an if command, then a series of -else if-, and then an -else- command at the end
It may be an obvious distinction, but I would appreciate if someone would explain it to me like I'm a 6 year old child
Let's take an example. I want to rename a variable based on the color of the thing it contains as a value.
The three following codes produce the same results :
Maybe that was just luck, but if it is I would like someone to explain me how it is luck and when should I use each of those different lines. Thanks for this very cool software !
I don't have a data problem in particular. I'm trying to learn about how Stata works and I find myself a bit puzzled by the if command. I get there's a difference between the if command and an if qualifier, but it's hard for me to understand the difference between :
1) a series of -if- commands
2) an if command, then a series of -else if- commands until the end,
3) an if command, then a series of -else if-, and then an -else- command at the end
It may be an obvious distinction, but I would appreciate if someone would explain it to me like I'm a 6 year old child

Let's take an example. I want to rename a variable based on the color of the thing it contains as a value.
Code:
* Example generated by -dataex-. For more info, type help dataex clear input str10(var1 var2 var3) "sea" "grass" "wood" end
Code:
foreach var of varlist * { local a = strpos(`var', "sea") local b = strpos(`var', "grass") local c = strpos(`var', "wood") if `a' > 0 { rename `var' blue } if `b' > 0 { rename `var' green } if `c' > 0 { rename `var' brown } }
Code:
foreach var of varlist * { local a = strpos(`var', "sea") local b = strpos(`var', "grass") local c = strpos(`var', "wood") if `a' > 0 { rename `var' blue } else if `b' > 0 { rename `var' green } else if `c' > 0 { rename `var' brown } }
Code:
foreach var of varlist * { local a = strpos(`var', "sea") local b = strpos(`var', "grass") local c = strpos(`var', "wood") if `a' > 0 { rename `var' blue } else if `b' > 0 { rename `var' green } else rename `var' brown }
Code:
. list, clean blue green brown 1. sea grass wood
Comment