4.1 Creating & Modifying Variables with Assignment Statements
Key Takeaways
- Assignment statements evaluate expressions on the right side of an equal sign and assign results to variables on the left side (variable = expression;) during DATA step execution.
- SAS automatically determines variable data types and byte lengths during compilation based on their first appearance in the DATA step unless explicitly declared with LENGTH or ATTRIB statements.
- Character variables created by assignment without a prior LENGTH declaration inherit the byte length of the first assigned string literal, causing subsequent longer string values to truncate silently.
- Performing arithmetic operations on missing numeric values (.) generates a missing value result and writes a diagnostic note to the SAS log without stopping program execution.
- The LENGTH statement must precede a variable's first reference in the DATA step compilation sequence to properly allocate storage bytes in the Program Data Vector (PDV).
4.1 Creating & Modifying Variables with Assignment Statements
Quick Answer: In SAS DATA step processing, an assignment statement evaluates an expression to the right of the equal sign and stores the resulting value in the variable specified to the left (
variable = expression;). If a variable does not already exist in the input dataset or Program Data Vector (PDV), SAS creates it during the compilation phase and establishes its data type (numeric or character) and byte length based on its first appearance. To prevent character string truncation or unexpected default lengths, always use aLENGTHstatement before assigning character values.
Anatomy of a SAS Assignment Statement
The assignment statement is the primary workhorse for data transformation in SAS. Its general syntax is:
variable = expression;
variable: The name of a new or existing SAS variable. SAS variable names must follow standard naming rules: 1 to 32 characters long, begin with a letter or underscore, and contain only letters, numbers, or underscores.=: The assignment operator that copies the evaluated result of the expression into the variable's storage location in the PDV.expression: A combination of constants, variable names, mathematical operators, SAS functions, or logical operators that evaluates to a single numeric or character value.
Execution Flow in the DATA Step Loop
Unlike macro variables or compile-time directives, assignment statements execute sequentially during the execution phase for every observation processed by the DATA step iteration loop.
data work.employee_salaries;
set sashelp.empdata;
/* Arithmetic assignment statement */
AnnualBonus = Salary * 0.15;
/* Character assignment statement */
BonusTier = 'Standard';
/* Expression combining existing and newly created variables */
TotalCompensation = Salary + AnnualBonus;
run;
When SAS compiles this DATA step:
- It scans the statement tokens and identifies
AnnualBonus,BonusTier, andTotalCompensationas new variables. - It adds these variables to the Program Data Vector (PDV).
- It assigns default attributes (Numeric 8 bytes for numbers; Character length equal to the first string assigned for characters).
- During execution, SAS reads a row from
sashelp.empdata, computes the expressions row-by-row, updates the PDV, and writes the output row.
Variable Attributes & Compilation Mechanics
Every SAS variable possesses four core attributes: Name, Type (Numeric or Character), Length (bytes in memory), and optional Format/Informat / Label.
How SAS Determines Attributes Automatically
If you do not explicitly declare variable attributes using a LENGTH or ATTRIB statement, SAS inspects the first statement where the variable appears during compilation:
- Numeric Variables: Assigned a default storage length of 8 bytes (double-precision floating-point format), accommodating up to 16 significant digits.
- Character Variables: Assigned a length equal to the length of the string result in its very first reference or assignment in the DATA step code.
The Character Truncation Pitfall
One of the most frequent traps on the SAS Base Programming exam involves implicit character variable sizing. Consider the following DATA step:
data work.status_assignment;
set work.orders;
/* First reference to variable Status */
if OrderAmount < 50 then Status = 'Low';
else if OrderAmount < 200 then Status = 'Medium';
else Status = 'High Priority';
run;
What Happens During Compilation?
- SAS reads the first assignment:
Status = 'Low';. - SAS determines
Statusis a character variable with length 3 (the byte length of'Low'). - SAS allocates exactly 3 bytes for
Statusin the PDV.
What Happens During Execution?
- When
OrderAmountis 150, SAS attempts to assign'Medium'(6 characters). BecauseStatusis fixed at 3 bytes, SAS truncates the value to'Med'without issuing any warning or error! - When
OrderAmountis 500,'High Priority'(13 characters) is truncated to'Hig'.
Resolving Truncation with the LENGTH Statement
To ensure proper byte allocation, place a LENGTH statement before the variable's first reference in the DATA step:
data work.status_fixed;
set work.orders;
/* Explicit length declaration MUST precede assignment */
length Status $ 13;
if OrderAmount < 50 then Status = 'Low';
else if OrderAmount < 200 then Status = 'Medium';
else Status = 'High Priority';
run;
Exam Rule: The
LENGTHstatement is a compile-time statement. Placinglength Status $ 13;at the bottom of the DATA step afterStatus = 'Low';will NOT work because compilation scans top-to-bottom and sets the PDV attributes on the first encounter.
Missing Values in Arithmetic Assignments
In SAS, numeric missing values are represented by a single period (.) or special missing characters (.A through .Z, ._). Character missing values are represented by a blank space (' ').
Propagation of Missing Values
When performing mathematical operations (+, -, *, /, **) in an assignment statement, if any operand in the expression is missing, the result of the entire expression evaluates to missing (.):
data work.calc_test;
BaseSalary = 60000;
Bonus = .; /* Missing numeric value */
/* Standard arithmetic operator assignment */
TotalComp1 = BaseSalary + Bonus; /* Evaluates to . */
/* SAS Function assignment */
TotalComp2 = sum(BaseSalary, Bonus); /* Evaluates to 60000 */
run;
When TotalComp1 = BaseSalary + Bonus; executes, SAS encounters the missing value for Bonus and performs the following actions:
- Assigns
TotalComp1 = .for that observation. - Writes a diagnostic note to the SAS log:
NOTE: Missing values were generated as a result of performing an operation on missing values.
Contrast: Arithmetic Operators vs. SAS Functions
| Feature | Arithmetic Operators (+, -, *, /) | SAS Summary Functions (SUM, MEAN, etc.) |
|---|---|---|
| Missing Value Handling | Propagates missing (50 + . = .) | Ignores missing values (sum(50, .) = 50) |
| All Operands Missing | Returns missing (. + . = .) | Returns missing (sum(., .) = .) |
| SAS Log Behavior | Writes NOTE: Missing values were generated... | Silent; no log notes generated |
| Syntax Example | Total = Q1 + Q2 + Q3 + Q4; | Total = sum(Q1, Q2, Q3, Q4); |
Formats vs. Stored Values in Assignments
A critical concept tested on the SAS Specialist exam is the difference between a variable's underlying stored value and its formatted display presentation.
data work.format_demo;
format SalePrice dollar10.2;
SalePrice = 1250.50;
/* Derived assignment statement */
Tax = SalePrice * 0.08;
DiscountedPrice = SalePrice - 100;
run;
- In memory,
SalePricestores the exact unformatted floating-point number1250.50. Taxis computed as1250.50 * 0.08 = 100.04, NOT based on formatted text.- Assigned variables do not automatically inherit formats from input variables.
TaxandDiscountedPricewill store raw unformatted numbers (100.04and1150.50) until explicitly assigned a format.
A SAS DATA step contains the statement Status = 'Pending'; as the first reference to the variable Status. Later in the same step, the statement Status = 'Approved-Final'; executes for a specific observation. What value is stored in Status for that observation?
Given the SAS dataset variables Salary = 50000 and Bonus = . (missing), what is the result of executing TotalComp = Salary + Bonus; in a DATA step?
Where must a LENGTH statement be placed relative to an assignment statement to ensure that a newly created character variable is allocated 20 bytes in the Program Data Vector (PDV)?
Consider the following SAS DATA step:
What is the stored raw numeric value of data work.eval;
format Rate 5.2;
Rate = 12.5;
Score = Rate * 2;
run;
Score in the output dataset?