110 likes | 232 Views
Lab 4 Wednesday, February 05, 2003. Manipulating Your Data with Boolean Logic and Iteration. Looping. Asking SAS to do something until a desired result is achieved.
E N D
Lab 4Wednesday, February 05, 2003 Manipulating Your Data with Boolean Logic and Iteration
Looping • Asking SAS to do something until a desired result is achieved. • “Rinse each dish, check to make sure it is clean. If it is, put it in the dishwasher; if not, repeat step 1. Stop when there are no dishes in the sink.”
IF test • Used to specify when a command should be used. • IF there are no dishes in the sink, don’t wash dishes. Go do the next item on your to-do list. • SAS format: IF <condition>; instruction; IF X < 20 THEN Y = 1; (Young people in group 1)
IF then DO • The IF loop can only perform one task. If you need to ask SAS to do several things if a condition is met, use a “IF then DO” statement. IF <condition> THEN DO; <task 1>; <task 2>; END;
IF X < 20 THEN DO; • Y = 1; • A = SQRT(B) + 4; • END;
WHILE loop • Performs a given task as long as the condition is true. • E.g.: While there are dishes in the sink; wash dishes. WHILE <condition> DO; <task1>; <task2>; END;
WHILE (_N_ LT 10) DO; • SUM=X1+X2+X3; • AVE = SUM/3; • END;
OUTPUT statement • Used within a loop to tell SAS to write that observation or case. • E.g.: “If that apple is good, store it; otherwise dump it. ” Output can also be used to write multiple observations from each input observation. IF <condition>; OUTPUT;
DROP statement • Used to drop VARIABLES (not cases) from the dataset. • Can be used to clean up datasets after adding “flags”, or to include only interesting variables for analysis. DROP age gender IQ;
Incrementing • Sometimes you want a set of instructions to be executed a certain number of times. • We use counter variables to keep track of the number of times an instruction set has been run. IF counter < 10 THEN DO; OUTPUT; counter = counter +1; END;
Retaining Variables • By default, SAS resets each variable when it reads another case. This really messes up our counter variables, so to prevent it we tell SAS to “retain” the value of these variables from case to case. • We can set the initial value of these variables in the same statement. (default is 0 ) RETAIN counter counter2 0 index 1;