Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

SAS Practice Exercises

Practice SAS with 12 graded exercises covering PROC steps, macro variables, PROC SQL and statistics, with solutions to read and runnable SQL and Python stand-ins to check your logic.

You learn SAS by writing it. This page has twelve exercises that mirror the second half of the course: procedures, macros, SQL and statistics. Try each one on paper or in your own SAS session first, then compare with the solution notes.

SAS cannot run on this site. Solutions to the SAS tasks are given as read-only code and I do not show output that I cannot guarantee. Two exercise groups have runnable stand-ins (SQL in SQLite and Python) so you can check your reasoning about the results.

Data for the exercises

Suppose work.emp has id, name, dept, salary, hired (a SAS date), and work.dept has dept and city. Several exercises use sashelp.class, a small table shipped with SAS (Name, Sex, Age, Height, Weight), so you can try them without importing anything.

Part 1: PROC steps

1. Print the first 8 observations of sashelp.class with only Name, Age and Height, without the Obs column.

2. Create work.by_age, sorted by Age ascending and Weight descending, without changing the original.

3. Show a frequency table of Sex and a cross-tabulation of Sex by Age, with row percents only.

4. Compute n, mean, min, max of Height and Weight per Sex, and save the result as a data set with one row per sex.

SQL Check the logic of exercise 4 in SQL

Press Run (or Ctrl + Enter) to see the result here.

Solutions in SAS:

SAS
/* 1 */ proc print data=sashelp.class (obs=8) noobs;
          var name age height;
        run;

/* 2 */ proc sort data=sashelp.class out=work.by_age;
          by age descending weight;
        run;

/* 3 */ proc freq data=sashelp.class;
          tables sex;
          tables sex * age / nocol nopercent;
        run;

/* 4 */ proc means data=sashelp.class noprint nway;
          class sex;
          var height weight;
          output out=work.stats n= mean= min= max= / autoname;
        run;

Exercise 2 sorts by age ascending, then weight descending: descending precedes only weight. Exercise 4 needs nway or the output also contains the overall row (_TYPE_ = 0), and autoname creates names such as Height_Mean.

Part 2: macros

5. Write a macro variable dsn holding sashelp.class and use it to print the data set in a PROC PRINT with the title "Data set: sashelp.class" (the title must show the macro variable's value).

6. Write a macro %top(ds, var, n=5) that prints the n rows with the largest values of var.

7. Write a macro that loops over the ages 11 to 16 and prints one PROC PRINT per age using where age = &a.

SAS
/* 5 */ %let dsn = sashelp.class;
        title "Data set: &dsn";
        proc print data=&dsn; run;
        title;

/* 6 */ %macro top(ds, var, n=5);
          proc sort data=&ds out=work._tmp;
            by descending &var;
          run;
          proc print data=work._tmp (obs=&n);
            title "Top &n by &var";
          run;
          title;
        %mend top;
        %top(sashelp.class, height, n=3)

/* 7 */ %macro by_age;
          %local a;
          %do a = 11 %to 16;
            proc print data=sashelp.class;
              where age = &a;
              title "Age &a";
            run;
          %end;
        %mend by_age;
        %by_age

Common errors: single quotes in the title (no resolution), %let with a semicolon inside the value, and forgetting %local a. For exercise 6 note that obs=&n is the last observation to print.

Part 3: PROC SQL

8. List each department with its employee count and average salary, but only departments with at least two employees, highest average first.

9. List employees earning more than the average salary of their own department.

10. Show every department with its city, including departments with no employees (employee count 0).

SQL Check your SQL for exercises 8 to 10

Press Run (or Ctrl + Enter) to see the result here.

The same statements work in proc sql; ... quit; after adding the library name (work.emp). Exercise 9 is a correlated subquery; in PROC SQL you can alternatively use the summary-function remerge (having salary > mean(salary) with a group by dept), but the subquery is clearer. Exercise 10 uses COUNT(e.id), not COUNT(*), to give 0 for LEGAL (the lesson on PROC SQL: Joins and Subqueries explains why).

Part 4: statistics

11. For sashelp.class, test whether the mean Height differs between the sexes and report whether to use the pooled or Satterthwaite row. Name the assumptions you would check.

12. Fit a regression of Weight on Height, and save the predictions and residuals. What would the residual plot look like if a straight line were wrong?

SAS
/* 11 */ proc ttest data=sashelp.class;
           class sex;
           var height;
         run;

/* 12 */ proc reg data=sashelp.class;
           model weight = height;
           output out=work.pred p=pred r=resid;
         run; quit;

For 11 read the equality-of-variances test first, but if in doubt use Satterthwaite. Check independence, rough normality (histogram or qqplot) and that the group sizes are not tiny. For 12, curvature in the residual-versus-predicted plot signals a non-linear relationship; a funnel shape signals unequal variance.

Stand-in: check the t statistic for exercise 11

Python Stand-in: pooled vs Welch t statistic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When the group sizes are equal, the two statistics are identical; they differ when sizes and variances both differ. That is why Satterthwaite is a safe default.

How to keep practicing

  • Re-solve each task in both a DATA step/PROC style and PROC SQL.
  • Break your own code on purpose (a missing semicolon, an unsorted BY) and read the log message.
  • Recreate a summary report from a spreadsheet you know well.
  • Write one macro that you actually reuse.
  • Return to PROC FORMAT and Custom Formats and recode a variable two ways.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which sort statement gives age ascending and weight descending?

    DESCENDING applies to the variable that follows it, so 'age descending weight' sorts weight high to low.
  2. 2. Why does a macro title need double quotes?

    Inside single quotes the macro variable stays as literal text.
  3. 3. Which count gives 0 for a department with no employees after a left join?

    COUNT(column) ignores missing values; COUNT(*) would count the unmatched row once.
  4. 4. What does a funnel shape in a residual plot suggest?

    Residual spread that grows with the predicted value violates the constant-variance assumption.

Summary

  • Practice all three styles: PROC steps, macros and PROC SQL, and learn to move between them.
  • descending binds to the next variable; nway and autoname shape PROC MEANS output.
  • Macro tasks need double quotes, %local and careful semicolons.
  • Count with COUNT(column) after outer joins; use correlated subqueries for group comparisons.
  • Check statistical assumptions, not just p-values.

Next: SAS Programming home page