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: , , , , , , , ,

Monday, March 30, 2020

🧱 Building Blocks in SAS: A Beginner's Guide to SAS Programming Structure

If you're just getting started with SAS programming, understanding the building blocks of SAS is the key to writing powerful and efficient code.

This guide will break down the fundamental components of SAS so you can confidently structure and run your first programs. These building blocks form the foundation of all SAS data manipulation, reporting, and analysis tasks.


πŸš€ What is SAS?

SAS (Statistical Analysis System) is a software suite used for advanced analytics, data management, and business intelligence. It's widely used in industries such as healthcare, banking, and pharmaceuticals.


πŸ”§ Core Building Blocks of a SAS Program

A SAS program is typically made up of the following major components:


1️⃣ DATA Step

The DATA step is used to create, read, and modify SAS datasets. It’s the most fundamental block where data preparation and manipulation happen.

βœ… Syntax:

data output_dataset;
set input_dataset; /* Data transformation logic */ run;

πŸ” Use Cases:

  • Reading data
  • Creating new variables
  • Filtering observations
  • Applying conditional logic


2️⃣ PROC Step

The PROC (Procedure) step calls SAS procedures to analyze and process data. SAS has procedures for sorting, printing, summarizing, plotting, and modeling data.

βœ… Syntax:

proc print data=dataset_name;
run;

πŸ” Common PROCs:

  • PROC PRINT: Displays data
  • PROC SORT: Sorts data
  • PROC MEANS: Summarizes statistics
  • PROC FREQ: Frequency tables
  • PROC SQL: SQL-like data manipulation


3️⃣ Statements

Statements are commands that perform specific tasks within a DATA or PROC step.

πŸ”Ή Examples:

  • SET: Reads data from a dataset
  • IF...THEN...ELSE: Conditional logic
  • KEEP/DROP: Include or exclude variables
  • INPUT and INFILE: Read raw external data
  • FORMAT and INFORMAT: Control data display and input

🧠 Example:

data age_flag;
set sashelp.class; if age >= 13 then flag = 'Teen'; else flag = 'Child'; run;

4️⃣ Functions

SAS provides built-in functions for mathematical, character, date/time, and statistical operations.

πŸ”Ή Common Functions:

  • SUM(), MEAN(): Math
  • SUBSTR(), UPCASE(): Character
  • TODAY(), INTNX(): Date/Time

🧠 Example:

data new;
set old; full_name = catx(' ', first_name, last_name); run;

5️⃣ Formats and Informats

  • Formats control how values are displayed.
  • Informats tell SAS how to read raw data.

🧠 Example:

data dates;
input dob mmddyy10.; format dob date9.; datalines; 01/01/1990 ; run;

6️⃣ Comments

Comments help explain code. They’re ignored during execution but essential for documentation.

πŸ“ Syntax:

/* This is a comment */
* This is also a comment; /* Semicolon is required */

🧩 Structure of a Complete SAS Program

Here’s how a simple SAS program typically looks:

/* Step 1: Create dataset */
data work.sales; input name $ sales; datalines; John 200 Jane 300 ; run; /* Step 2: Print dataset */ proc print data=work.sales; run;

πŸ“ Optional Building Blocks

These aren't mandatory in every program but are helpful in organizing larger SAS projects:

πŸ”Ή LIBNAME Statement

Defines a library (a folder or path where datasets are stored).

libname mylib 'C:\SASData';

πŸ”Ή Macro Language

For dynamic, reusable code. Example:

%let year = 2025;
proc print data=sales&year.; run;

🧠 Tips for Beginners

  • Always end statements with a semicolon (;)
  • Use RUN; or QUIT; to execute a block
  • Check the Log Window for errors
  • Start small, and gradually learn PROCs and functions


βœ… Summary

Building BlockPurpose
DATA StepCreate and manipulate datasets
PROC StepPerform analysis using procedures
StatementsControl the flow and logic of your code
FunctionsPerform calculations or transformations
FormatsDisplay data in a readable format
CommentsExplain code for future reference
LIBNAME/MacrosOrganize and automate SAS projects

πŸ“Œ Final Thoughts

Understanding the building blocks of SAS sets you up for success in analytics, reporting, and automation. Whether you're a data analyst, clinical programmer, or preparing for SAS certification, these fundamentals will stay with you throughout your SAS journey.

Labels: , , , ,