Tuesday, August 5, 2025

πŸ”„ Mastering IF-THEN-ELSE and DO Loops in SAS – Complete Guide with Examples

πŸ”° Introduction

Conditional logic and looping are core concepts in any programming language. In SAS, IF-THEN-ELSE statements and DO loops provide powerful tools for controlling the flow of your Data Step code. This guide explains how to use these tools effectively with real-world examples.


If else in SAS

🧩 1. IF-THEN-ELSE in SAS

The IF-THEN-ELSE statement allows you to execute specific code based on conditions.

βœ… Syntax:

IF condition THEN action;
ELSE IF condition THEN action; ELSE action;

πŸ“Œ Example 1: Simple IF-THEN-ELSE

data class_flag;
set sashelp.class; if age < 13 then group = 'Child'; else if age < 18 then group = 'Teen'; else group = 'Adult'; run;

Explanation:
Classifies students into Child, Teen, or Adult groups based on age.


πŸ§ͺ More IF-THEN-ELSE Examples in SAS


πŸ“Œ Example 1: Assign Grades Based on Scores

data grades;
input name $ score; if score >= 90 then grade = 'A'; else if score >= 80 then grade = 'B'; else if score >= 70 then grade = 'C'; else if score >= 60 then grade = 'D'; else grade = 'F'; datalines; John 85 Sara 92 Alex 67 Nina 74 Bob 58 ; run;

πŸ“Œ Example 2: Handle Missing Values in Conditions

data test_missing;
input id age; if age = . then status = 'Missing'; else if age < 18 then status = 'Minor'; else status = 'Adult'; datalines; 1 25 2 . 3 17 ; run;

πŸ“Œ Example 3: Create Flags for Categorical Variables

data product_flag;
input product $ category $; if category = 'Electronics' then flag = 1; else flag = 0; datalines; Laptop Electronics Shoes Apparel Phone Electronics Watch Accessories ; run;

πŸ“Œ Example 4: Nested IF-THEN-ELSE Logic

data nested_logic;
input city $ temp; if city = 'Delhi' then do; if temp > 40 then warning = 'Heatwave'; else warning = 'Normal'; end; else warning = 'Check city'; datalines; Delhi 45 Delhi 30 Mumbai 32 ; run;

πŸ“Œ Example 5: Use with Multiple Variables

data risk_check;
input age income; if age < 25 and income < 30000 then risk = 'High'; else if age >= 25 and income < 30000 then risk = 'Medium'; else risk = 'Low'; datalines; 22 25000 28 28000 35 60000 ; run;

πŸ“Œ Example 6: Case-Insensitive Character Comparison

data department;
input empname $ dept $; if upcase(dept) = 'HR' then team = 'Human Resources'; else team = 'Other'; datalines; John HR Alex finance Sara hr ; run;

πŸ“Œ Example 7: Assign Labels to Numeric Ranges

data salary_bracket;
input empid salary; if salary < 30000 then bracket = 'Low'; else if 30000 <= salary < 60000 then bracket = 'Medium'; else bracket = 'High'; datalines; 101 25000 102 32000 103 60000 104 58000 ; run;

πŸ“Œ Example 8: IF Without ELSE (Slower)

Data no_else;
set sashelp.class; if age < 12 then group = 'Preteen'; if age >= 12 then group = 'Teen'; run;

πŸ’‘ Best Practices:

  • Use IF-THEN/ELSE instead of multiple IF statements for better performance.
  • When checking for missing values, use IF var = ..


πŸ”„ 2. DO Loops in SAS

DO loops are used to repeat code a specified number of times or while a condition is true.


βœ… 2.1 DO Loop Syntax

do index = start to end;
/* repeated statements */ end;

πŸ“Œ Example 2: Basic DO Loop

data loop_example;
do i = 1 to 5; square = i**2; output; end; run;

Explanation:
Generates a dataset with numbers 1 to 5 and their squares.


βœ… 2.2 DO WHILE Loop

data do_while;
x = 1; do while (x < 5); square = x**2; output; x + 1; end; run;

βœ… 2.3 DO UNTIL Loop

data do_until;
x = 1; do until (x > 5); cube = x**3; output; x + 1; end; run;

🧠 Combining IF and DO Loops

data even_numbers;
do i = 1 to 10; if mod(i, 2) = 0 then output; end; run;

Explanation:
Generates only even numbers between 1 and 10 using both DO loop and IF condition.


⚠️ Common Mistakes to Avoid

MistakeFix
Missing OUTPUT in DO loopAlways include output; if needed
Forgetting semicolonsEnd each SAS statement with ;
Using multiple IF instead of IF-THEN-ELSECan slow performance

πŸ”š Conclusion

Mastering IF-THEN-ELSE and DO loops in SAS empowers you to create dynamic, flexible, and readable data processing routines. Whether you're classifying data, creating new variables, or iterating through logic, these tools are fundamental to writing efficient SAS programs.

Labels: , , , , , , , ,

Tuesday, January 5, 2021

Understanding NOOBS, OBS=, N, and N in SAS Programming

When working with datasets in SAS, it's important to control data processing and output efficiently. SAS provides several options and automatic variables that help manage how data is read, processed, and displayed. In this post, we’ll explore four commonly used features:

  • NOOBS option in PROC PRINT
  • OBS= system option
  • _N_ automatic variable
  • N option in PROC MEANS or PROC FREQ

Let’s understand each with examples.

Use of NOOBS  

It is used for Suppress column which tells the row/observation number in Proc print.

Example - See both outputs with NOOBS and without NOOBS

Proc Print Data=SASHELP.CARS;
WHERE MAKE='Audi';
RUN;

Proc Print Data=SASHELP.CARS NOOBS;
WHERE MAKE='Audi';
RUN;

Use of Noobs

OBS= System Option

The OBS= option limits the number of observations that SAS reads from a dataset.

Syntax:
options obs=5;

Example:
options obs=5;
proc print data=sashelp.class;
run;

 Use of OBS  and N options - 

OBS option give the Actual row number from the original dataset, for example in below code output, row number starts from 8 because First row of Audi car in source dataset is available at 8th position


Proc PRINT data=SASHELP.cars N OBS;
where Make='Audi';
run;

Use of OBS and N - Datahark

N Option gives the Total count of observation in dataset.

Use of _N_ 

As I already explained in  my previous post for PDV - there are two automatic variables are being created in datastep these are - _N_ and _ERROR_

_N_ counts the Number of times Datastep begin to execute.

For Example - if we want to print the top 10 rows of any dataset - 

data test;
set SASHELP.CARS;
N=_N_;
if _n_<=10;
run;

Use of _N_ = Datahark

Summary Table

FeatureUsagePurpose
NOOBSIn PROC PRINTHide observation numbers in output
OBS=Global system optionLimit records read from datasets
_N_In DATA stepsCount iteration, control row logic
NIn summary proceduresDisplay count of non-missing values

Final Thoughts

These options and variables are small but powerful tools in a SAS programmer’s toolkit. Whether you're generating cleaner reports with NOOBS, testing code with OBS=, controlling logic with _N_, or summarizing data using N, understanding their usage can significantly enhance your efficiency in SAS.

Labels: , , , , , , , ,