МатематикаМоя статистика
Тест по SAS
100 вопросов в 11 темах (лёгкий — 35, средний — 40, сложный — 25). Выберите темы, уровень и количество вопросов — к каждому ответу есть объяснение.
DATA step, чтение данных, форматы и даты, MERGE, функции, PROC SQL, описательная статистика, статистические процедуры, макросы и ODS. Вопросы на английском.
Все вопросы теста 100
Нажмите на вариант ответа, чтобы проверить себя, или «Показать ответ».
DATA step basics10
Which of these is a valid SAS variable name (default VALIDVARNAME=V7)?
- _score2
- 2score
- score-2
- total score
SAS names (up to 32 characters) must start with a letter or underscore and contain only letters, digits and underscores. '2score' starts with a digit, 'score-2' would be read as score minus 2, and 'total score' contains a blank.
Where is the data set created by this step stored?
data scores;
set raw;
run;- In SASUSER; it is kept permanently
- In the current folder as a permanent file scores.sas7bdat
- Only in memory until the next RUN statement
- In the temporary WORK library; it is deleted when the SAS session ends
A one-level name such as scores means WORK.scores. WORK is a temporary library that is erased at the end of the session. To keep a data set, use a two-level name with a library assigned by LIBNAME, e.g. mylib.scores.
Data set a has one variable x with values 1, 2, 3. What is the value of total in the last observation of b?
data b;
set a;
total = total + x;
run;- 6
- 3
- .
- 0
A variable created by an assignment statement is reset to missing at the start of every iteration, and missing + anything is missing, so total is . in every observation. Expecting 6 is the typical mistake of assuming the value carries over — use RETAIN total 0; or the sum statement total + x; for a running total.
Which statement about the automatic variable _N_ is true?
- It holds the number of observations in the input data set, known at compile time
- It counts the iterations of the DATA step and is not written to the output data set
- It is written to the output data set unless you drop it
- It increases only when an observation is written to the output
_N_ starts at 1 and increases by one each time the DATA step loops back to the top. Like _ERROR_ it lives in the PDV but is never written out (assign it to another variable to keep it). The total number of observations is what the NOBS= option of SET gives, and with a subsetting IF _N_ still counts every iteration, not only the written rows.
Data set a has x = 1, 2, 3. What does b contain?
data b;
set a;
if x > 1 then output;
y = 10;
run;- 2 observations, with y = 10 in both
- 2 observations, with y missing in both
- 3 observations, with y = 10 in all of them
- 3 observations, with y missing only in the first
An explicit OUTPUT statement anywhere in the step switches off the implicit OUTPUT, so only the rows with x > 1 are written — 2 of them. They are written at the moment OUTPUT executes, before y = 10 runs, and y (not retained) was reset to missing at the top of the iteration. The '3 observations' answers assume the implicit OUTPUT still happens.
In a DATA step that contains no OUTPUT statement, when is an observation written to the output data set?
- At the end of each iteration of the DATA step
- Once, after the last input observation has been read
- Each time an assignment statement executes
- Only when a PUT statement executes
Without an explicit OUTPUT, SAS adds an implicit OUTPUT at the bottom of the step: every pass through the code writes the current PDV contents as one observation, then control returns to the top. Writing only once at the end is something you program yourself (e.g. with END= and RETAIN); PUT writes to the log or a file, not to a data set.
What is the program data vector (PDV)?
- The descriptor portion of a data set stored on disk
- The list of macro variables available to the DATA step
- A buffer that holds all observations of the input data set at once
- The area of memory where SAS builds the current observation, one at a time
During execution SAS reads one observation into the PDV, runs your statements on those values and writes the PDV to the output data set. The descriptor portion (names, types, lengths) is metadata stored with the data set, and the DATA step never loads the whole input into memory.
Data set a has x = 1, ., 3 (three observations). What are the values of total in b?
data b;
set a;
total + x;
run;- 1, ., .
- 1, 1, 4
- 1, ., 4
- 4, 4, 4
The sum statement total + x; implies RETAIN total with initial value 0 and adds x like SUM() does, ignoring a missing x: 0 + 1 = 1, then 1 (missing skipped), then 1 + 3 = 4. '1, ., .' is what a retained total = total + x would give, because missing propagates through +; '4, 4, 4' confuses a running total with a grand total.
Data set a contains x and y (y = 5 in every row). What is z in data set b?
data b;
set a(drop=y);
z = y * 2;
run;- 10 in every observation
- 0 in every observation
- The step fails with an error because y does not exist
- Missing in every observation, with a note that y is uninitialized
The DROP= data set option on the input means y is never read into the PDV. The reference y * 2 then creates a new numeric variable y that is always missing (NOTE: Variable y is uninitialized), so z is missing. A DROP statement or DROP= on the output data set would be different: y would be read and used, and only left out of b.
Data set a has 3 observations (x is not one of its variables). How many observations does b have?
data b;
x = 1;
output;
set a;
run;- 3
- 6
- 4
- 7
Because an OUTPUT statement is present there is no implicit OUTPUT — one row per iteration. Iterations 1–3 each output and then read a row. In iteration 4 the OUTPUT executes first (writing a fourth row, with a's last values still in the PDV because variables read by SET are retained), and only then SET hits end of file and stops the step. 6 or 7 assume an extra implicit OUTPUT; 3 forgets that the step stops at the SET, not at the top.
Reading data9
What does FIRSTOBS=2 do here?
data sales;
infile '/data/sales.csv' dlm=',' firstobs=2;
input region $ amount;
run;- Reads only the first 2 lines of the file
- Skips the first 2 data lines after the header
- Starts reading at the second line of the file, skipping the header row
- Reads every second line of the file
FIRSTOBS=n tells INFILE which record to start with; for a CSV with a header line, FIRSTOBS=2 skips it. Limiting how many lines are read is the job of the OBS= option, which gives the number of the last line to read.
What value does name get?
data p;
input name $ age;
datalines;
Christopher 25
;
run;- Christopher
- Chris
- Missing, with an 'Invalid data' note
- Christop
With list input and no LENGTH statement or informat, a character variable gets the default length of 8 bytes, so 'Christopher' is truncated to 'Christop'. Declare length name $ 20; before INPUT (or use the modified informat name :$20.) to keep the full value.
What values do a, b and c get?
data t;
infile datalines dsd;
input a b c;
datalines;
1,,3
;
run;- a = 1, b = ., c = 3
- a = 1, b = 3, c = .
- a = 1, b = 0, c = 3
- All three missing, with an 'Invalid data' note
DSD makes the comma the default delimiter and treats two consecutive delimiters as a missing value between them, so b is missing. With only DLM=',' (no DSD), consecutive delimiters count as one and 3 would land in b — the classic bug when reading CSV files with empty fields.
What does the DATA step produce for this data line?
data t;
input name $ age;
datalines;
Mary Ann 42
;
run;- name = 'Mary Ann', age = 42
- name = 'Mary', age = 42
- name = 'Mary', age = . with an 'Invalid data' note
- An error, and the DATA step stops
List input splits on blanks, so name gets 'Mary' and age tries to read 'Ann', which is not a number: age is set to missing, _ERROR_ is set to 1 and the log shows 'Invalid data for age'. The step keeps running. To read embedded blanks use the & modifier (name & $20.) with two blanks before the next field, or column/formatted input.
What does the $ after name mean in this INPUT statement?
data people;
input name $ age;
datalines;
Anna 34
Boris 41
;
run;- name is read as a character variable
- name holds a currency amount
- name is a macro variable
- name is the key used for BY-group processing
In list input a $ after the variable name declares it character. Without it SAS expects a number and would set name to missing with an 'Invalid data' note. Currency values are read with informats such as DOLLARw.d or COMMAw.d, not with $.
How many observations does nums have?
data nums;
input x @@;
datalines;
1 2 3
4 5
;
run;- 2
- 3
- 5
- 1
The double trailing @@ holds the data line across iterations, so each iteration reads the next value from the same line until it is used up: 1, 2, 3, then 4, 5. Without @@ each iteration would start a new line and read only its first value, giving 2 observations (1 and 4).
What numeric value is stored in amount?
data t;
input @1 sdate mmddyy10. @12 amount comma8.;
datalines;
03/15/2024 1,250.50
;
run;- 1
- 1250.5
- 125050
- Missing, because a comma is not a valid digit
The COMMAw.d informat removes commas (and dollar signs, blanks and parentheses) before converting, so '1,250.50' becomes 1250.5. The plain w.d informat would stop at the comma and give a missing value with an 'Invalid data' note; 125050 would mean the decimal point had been thrown away too.
How many observations does t have?
data t;
input a b c;
datalines;
1 2
3 4 5
6 7 8
;
run;- 2, the first being a = 1, b = 2, c = 3
- 3, with c missing in the first
- 2, the second being a = 4, b = 5, c = 6
- 1
The default FLOWOVER behaviour: when a line runs out of values, INPUT continues on the next line, so the first observation takes 1, 2 and then 3 from line two. The rest of that line (4 5) is discarded because the next iteration starts on a new line, so line three gives the second observation. 'c missing in the first' is what MISSOVER or TRUNCOVER on an INFILE statement would produce.
What values are read? (There are two blanks before 42.)
data t;
input name & $20. age;
datalines;
Mary Ann Smith 42
;
run;- name = 'Mary', age = .
- name = 'Mary Ann Smith 42', age = .
- name = 'Mary Ann Smith', age = .
- name = 'Mary Ann Smith', age = 42
The & modifier lets a list-input character value contain single blanks; the value ends at two or more consecutive blanks. The informat $20. sets the length, but as modified list input it does not force SAS to read exactly 20 columns, so age is still read as 42. Without & the name would stop at the first blank.
Variables and formats9
How does SAS store a date value such as 15 March 2024?
- As a number: the count of seconds since 1 January 1960
- As a number: the count of days since 1 January 1960
- As a number: the count of days since 1 January 1900
- As a character string such as '15MAR2024'
A SAS date is a plain numeric value: days since 01JAN1960 (that day is 0, earlier dates are negative). Seconds since 1960 is a SAS datetime value; days since 1900 is the Excel convention. Formats such as DATE9. only change how the number is displayed.
What is the default length, in bytes, of a numeric variable in a SAS data set?
- 8
- 4
- 2
- 16
Numeric values are stored as 8-byte floating-point numbers by default, which gives about 15–16 significant digits. A LENGTH statement can shorten them (3 bytes is the minimum on Windows and Unix), at the cost of precision for non-integers.
What value is stored in d?
data t;
d = '31DEC1959'd;
run;- 0
- 364
- Missing, because dates before 1960 are not allowed
- -1
Date constants are counted from 01JAN1960 = 0, so the day before is -1. Dates back to 1582 are valid — they are simply negative numbers. 0 is 1 January 1960 itself.
What does the PUT statement write to the log?
data _null_;
d = '15MAR2024'd;
put d yymmdd10.;
run;- 15MAR2024
- 03/15/2024
- 2024-03-15
- 23450
YYMMDD10. writes year-month-day separated by dashes. 15MAR2024 is what DATE9. writes, 03/15/2024 is MMDDYY10., and 23450 is the unformatted stored value (days since 01JAN1960).
In data set raw, name is character with length 20. What is the length of name in data set t?
data t;
set raw;
length name $ 10;
run;- 10, with values truncated to 10 characters
- 20, and the log warns that the length was already set
- 30, the two lengths added together
- The step fails with an error and t is not created
LENGTH only takes effect at a variable's first reference during compilation. Here SET has already defined name with length 20, so the later LENGTH statement is ignored with a WARNING ('Length of character variable name has already been set'). To shorten it, put the LENGTH statement before SET.
Which statement is true after this step?
data t;
x = 1234.567;
format x 8.1;
run;- The stored value is rounded to 1234.6
- The stored value is 1234.567; PROC PRINT displays 1234.6
- The stored value is truncated to 1234.5
- x becomes a character variable '1234.6'
A format controls only how a value is written; the full value stays stored and is used in calculations. To change the stored value use ROUND(x, 0.1). Truncation to 1234.5 would be wrong anyway — the 8.1 format rounds when it displays.
What does this LABEL statement change?
data t;
set raw;
label sbp = 'Systolic blood pressure';
run;- It renames sbp to 'Systolic blood pressure'
- It assigns a display format to sbp
- It only adds a comment line to the log
- The descriptive text shown for sbp in procedure output; the variable is still named sbp
A label is metadata stored with the variable and used by most procedures in their output (PROC PRINT needs the LABEL option). Code still refers to the variable as sbp; changing the name is done with RENAME, and display formats with FORMAT.
What is the value of status?
data t;
x = 2;
if x = 1 then status = 'No';
else status = 'Yes';
run;- 'Ye'
- 'Yes'
- 'No'
- Missing (blank)
The length of a character variable is fixed at compile time by its first reference: status = 'No' gives it length 2, no matter which branch runs. 'Yes' is therefore truncated to 'Ye'. Put length status $ 3; before the IF statement.
age is missing (.) in one observation. What does PROC PRINT show for it?
proc format;
value agegrp low-<18 = 'Minor'
18-high = 'Adult';
run;
proc print data=t;
var age;
format age agegrp.;
run;- Minor
- Adult
- .
- An error, because missing is not covered by any range
For numeric formats the keyword LOW does not include missing values (it does for character formats). A value that no range covers is shown with the default format, so the missing age prints as a period. Expecting 'Minor' comes from the fact that missing sorts below every number — true for comparisons and sorting, but not for LOW in PROC FORMAT. Add . = 'Unknown' (or OTHER =) to label it.
Conditional logic and loops9
What does the statement if sex = 'F'; do in this DATA step?
data women;
set patients;
if sex = 'F';
run;- Sets sex to 'F' in every observation
- Writes all observations and adds a flag variable
- Stops the whole DATA step at the first observation that is not 'F'
- Writes only the observations where sex is 'F'; for the others the iteration ends without output
A subsetting IF (no THEN) lets the current iteration continue only when the condition is true; otherwise SAS returns to the top and the implicit OUTPUT is skipped. It does not end the whole step (that is STOP) and it is not an assignment. The comparison is case-sensitive: 'f' would not match.
What is the value of i after the loop finishes?
data t;
do i = 1 to 5;
total + i;
end;
run;- 6
- 5
- 15
- .
An iterative DO increments the index and then tests it against the stop value: after the pass with i = 5, i becomes 6, the test fails and the loop ends, so i = 6 is written. 15 is the value of total.
What does this code do?
data clean;
set survey;
array q{3} q1-q3;
do i = 1 to 3;
if q{i} = 99 then q{i} = .;
end;
drop i;
run;- Replaces the code 99 with a missing value in q1, q2 and q3
- Creates three new variables q{1}, q{2}, q{3} holding 99
- Deletes observations in which any of q1–q3 equals 99
- Replaces missing values in q1–q3 with 99
An ARRAY is just a temporary name for a group of existing variables, so q{i} refers to q1, q2 and q3 in turn; nothing new is stored. The loop recodes the 99 'no answer' code to missing and the observation is kept. Without the DROP the index variable i would be written out too.
grade is 'C' in one observation. What happens?
data t;
set grades;
select (grade);
when ('A', 'B') points = 2;
when ('D') points = 0;
end;
run;- points is set to missing and processing continues
- SAS writes an error to the log and the DATA step stops
- points is set to 0, the value of the last WHEN
- The observation is silently deleted
When no WHEN expression matches and there is no OTHERWISE statement, SAS reports an error (unsatisfied WHEN clause) and stops the step. Always add an OTHERWISE — even an empty otherwise; — if some values may fall through. An IF/ELSE IF chain, by contrast, simply does nothing when no condition is true.
What is the value of y?
data t;
x = 5;
if x > 3 then y = 1;
else if x > 4 then y = 2;
else y = 3;
run;- 2
- 1
- 3
- .
An ELSE IF chain stops at the first true condition. x > 3 is already true, so y = 1 and the later branches are skipped even though x > 4 is true as well. Put the most specific condition first if you want y = 2.
How many observations does t have?
data t;
do i = 1 to 3;
x = i * 10;
output;
end;
run;- 3
- 1
- 4
- 6
OUTPUT inside the loop writes one observation per pass: (1, 10), (2, 20), (3, 30). With no SET or INPUT the step runs only once. Without the OUTPUT statement you would get 1 observation (i = 4, x = 30), written by the implicit OUTPUT after the loop.
age is missing for one patient. What is group for that patient?
data t;
set patients;
length group $ 5;
if age < 18 then group = 'child';
else group = 'adult';
run;- 'adult'
- Blank, because a comparison with missing is skipped
- The step stops with an error
- 'child'
A missing numeric value is smaller than any number, so age < 18 is true and the patient falls into 'child' — a very common bug. Guard against it with if missing(age) then ...; or if . < age < 18 then ...;.
What is the value of n?
data t;
n = 0;
x = 10;
do until (x > 5);
n + 1;
end;
run;- 0
- 6
- 1
- The loop never ends
DO UNTIL tests its condition at the bottom of the loop, so the body always runs at least once: n becomes 1, then x > 5 is true and the loop stops. A DO WHILE (x <= 5) would test at the top and run 0 times.
What happens when this step runs?
data t;
array a{3} x1-x3;
do i = 1 to 4;
a{i} = 0;
end;
run;- SAS creates x4 = 0 automatically
- The fourth assignment is ignored and t has x1–x3 = 0
- The subscript wraps around and sets x1 again
- An 'Array subscript out of range' error occurs at i = 4 and the step stops
Array bounds are fixed at compile time. Referencing a{4} at run time is an execution error: SAS writes 'Array subscript out of range' and the PDV contents to the log and stops the step. Arrays never grow and never wrap around. Use do i = 1 to dim(a); to stay within bounds.
Combining data sets9
a has 3 observations and b has 4, both with the same variables. How many observations does c have?
data c;
set a b;
run;- 4
- 3
- 12
- 7
Listing several data sets in one SET statement concatenates them: all rows of a, then all rows of b. 3 is what two separate SET statements (one-to-one reading) would give, stopping at the shorter data set; 12 would be a Cartesian product, which SET never forms.
a has id = 1, 2, 3 and b has id = 2, 3, 4 (one row per id, both sorted). Which ids are in c?
data c;
merge a(in=ina) b(in=inb);
by id;
if ina and not inb;
run;- 2 and 3
- 4
- 1
- 1 and 4
An IN= variable is 1 when the current BY group has a row from that data set. ina and not inb keeps ids found only in a, i.e. 1. '2 and 3' is the inner join (if ina and inb); '1 and 4' would be the non-matches from either side (if ina ne inb).
Both a and b have a variable score besides id. For id = 5, score is 70 in a and 85 in b. What is score in c for id = 5?
data c;
merge a b;
by id;
run;- 70
- The step fails because score appears in both data sets
- Two variables are created: score and score2
- 85
MERGE reads a and then b into the same PDV, so a common non-BY variable is overwritten by the data set listed last — 85. SAS neither stops nor renames anything; to keep both values rename one of them, e.g. b(rename=(score=score_b)).
An id has 3 rows in visits (sorted by id). What is n for that id in counts?
data counts;
set visits;
by id;
if first.id then n = 0;
n + 1;
if last.id;
keep id n;
run;- 1
- 3
- The running count of rows across all ids so far
- .
The sum statement retains n, and n is reset to 0 at the start of each id group, so on the last row of the group n equals the number of rows, 3. Without the first.id reset n would keep growing across ids; 1 would need n to be reset on every row.
a has 5 observations and b has 3. How many observations does c have?
data c;
set a;
set b;
run;- 3
- 5
- 8
- 15
Two SET statements read one row from each data set per iteration (one-to-one reading). The step stops as soon as any SET tries to read past its end — on the 4th iteration, for b — so only 3 rows are written. 8 would be concatenation (set a b;). Variables with the same name take the value read last, from b.
What must be true before running this step?
data both;
merge a b;
by id;
run;- a and b have the same number of observations
- id is a character variable
- Both a and b are sorted (or indexed) by id
- a and b have no variables in common except id
Match-merging with BY needs each data set in BY order (sorted with PROC SORT or indexed); otherwise SAS stops with 'BY variables are not properly sorted'. The data sets may differ in size, id may be numeric or character (the same type in both), and shared non-BY variables are allowed — the later data set's values overwrite.
a has one row: id = 1, x = 10. b has three rows with id = 1 and y = 1, 2, 3. What does c contain?
data c;
merge a b;
by id;
run;- 3 rows, each with x = 10
- 3 rows, with x = 10 only in the first
- 1 row with x = 10 and y = 3
- 1 row with x = 10 and y = 1
In a one-to-many merge the single row of a is read once and its values stay in the PDV (variables read by MERGE are retained) while the other rows of the BY group come from b. So x = 10 repeats on all three rows. Values are reset to missing only when the BY group changes.
visits is sorted by id and visit_date. What does last_visit contain?
data last_visit;
set visits;
by id;
if last.id;
run;- Only the very last row of the data set
- One row per id: its latest visit
- One row per id: its earliest visit
- All rows except the last one of each id
BY creates temporary variables first.id and last.id, equal to 1 on the first and last row of each id group. With dates sorted within id, the subsetting IF last.id; keeps each patient's latest visit; first.id would keep the earliest. first./last. variables are not written to the output.
a has 2 rows with id = 1 (x = 1, 2); b has 3 rows with id = 1 (y = 'p', 'q', 'r'). How many rows does c have?
data c;
merge a b;
by id;
run;- 6
- 3
- 2
- 5
MERGE pairs rows within a BY group one-to-one and never forms all combinations: (1, p), (2, q), and then x keeps its last value 2 for (2, r). SAS writes a NOTE that more than one data set has repeats of BY values. All 6 combinations would come from a PROC SQL join.
Functions9
What does mean(1, ., 3) return?
- 1.3333333
- .
- 2
- 4
MEAN averages only the non-missing arguments: (1 + 3) / 2 = 2. Dividing by all three arguments would give 1.33, (1 + . + 3) / 3 written with operators would give missing, and 4 is the sum.
What does scan('John A. Smith', -1, ' ') return?
- 'John'
- 'Smith'
- 'A.'
- A blank value
SCAN returns the n-th word, and a negative n counts from the right, so -1 is the last word, 'Smith'; 1 would give 'John'. Only the blank is a delimiter here, so the period stays part of the word 'A.'.
first = 'Ann' and last = 'Lee' are both stored with length 10. Which expression returns 'Ann Lee' with exactly one blank and no trailing blanks?
- catx(' ', first, last)
- first || ' ' || last
- cat(first, ' ', last)
- trim(first || last)
CATX strips leading and trailing blanks from every argument and puts the separator between them. || and CAT keep the trailing blanks of the length-10 values, so 'Ann' is followed by 7 blanks before ' Lee'. trim(first || last) removes blanks only at the very end, leaving those after 'Ann'.
What value does n get?
n = intck('month', '31JAN2024'd, '01FEB2024'd);- 0
- 0.03
- -1
- 1
By default INTCK counts the interval boundaries crossed, not whole intervals: from 31 January to 1 February one month boundary is crossed, so the result is 1 although only one day has passed. For complete elapsed months use the continuous method, intck('month', d1, d2, 'c'), which returns 0 here.
x is missing and y = 5. What are a and b?
data t;
x = .;
y = 5;
a = x + y;
b = sum(x, y);
run;- a = 5, b = 5
- a = ., b = .
- a = ., b = 5
- a = 5, b = .
Arithmetic operators propagate missing values: . + 5 is missing (with the note 'Missing values were generated'). Statistical functions such as SUM, MEAN, MIN and MAX ignore missing arguments, so SUM(x, y) = 5; SUM returns missing only when all arguments are missing.
What does substr('Statistics', 3, 4) return?
- 'atis'
- 'tati'
- 'tist'
- 'at'
SUBSTR(string, position, length): start at character 3 ('a') and take 4 characters — a, t, i, s. 'tati' and 'tist' are off-by-one starts (positions 2 and 4); 'at' treats the third argument as an end position, but it is a length.
c is the character value '123'. Which statement creates a numeric variable n = 123 without automatic type conversion?
- n = put(c, 8.);
- n = c;
- n = numeric(c);
- n = input(c, 8.);
INPUT(source, informat) reads a character value with an informat and returns a number. PUT(value, format) goes the other way and always returns a character value. n = c simply makes n another character variable, and there is no NUMERIC() function.
What does mdy(2, 30, 2024) return?
- A missing value, with a note about an invalid argument
- The date value of 1 March 2024
- The date value of 29 February 2024
- An error that stops the DATA step
MDY builds a date from month, day and year. 30 February does not exist, so the result is missing and the log reports 'Invalid argument to function MDY' — the step continues, and SAS does not roll over into March or clamp to the last day. Use INTNX to move between dates safely.
What date does intnx('month', '15MAR2024'd, 1) return?
- 15 April 2024
- 1 April 2024
- 30 April 2024
- 16 March 2024
INTNX moves a date by a number of intervals and by default aligns the result to the beginning of the interval: one month after March 2024 is April, aligned to 01APR2024. Use the 'same' alignment for 15APR2024 or 'end' for 30APR2024.
PROC SQL9
Which statement ends a PROC SQL step?
- run;
- end;
- quit;
- %mend;
PROC SQL executes each statement as soon as it is submitted and stays active until QUIT (or the next step boundary). RUN; is ignored with a note; END closes DO/SELECT blocks and %MEND closes a macro definition.
sales has 5 rows; score is missing in 2 of them. What does the query return?
proc sql;
select count(*) as n_all, count(score) as n_score
from sales;
quit;- n_all = 5, n_score = 5
- n_all = 3, n_score = 3
- n_all = 5, n_score = 2
- n_all = 5, n_score = 3
COUNT(*) counts rows; COUNT(column) counts only the non-missing values of that column. 2 is the number of missing values, which NMISS(score) would return.
Why does this query fail?
proc sql;
select price * qty as revenue,
revenue * 0.2 as tax
from orders;
quit;- revenue is not a column of orders; it must be referenced as calculated revenue
- An AS alias must be enclosed in quotes
- Arithmetic is not allowed in a SELECT list
- The query needs a GROUP BY clause
An alias created in the SELECT list is not a table column, so using it again in the same SELECT (or in WHERE) gives 'The following columns were not found'. SAS SQL provides the CALCULATED keyword for this: calculated revenue * 0.2 as tax.
What does this code do?
proc sql noprint;
select count(*) into :nobs
from patients;
quit;
%put &nobs;- Creates a data set nobs with one row
- Creates a numeric DATA step variable nobs in patients
- Stores the number of rows of patients in macro variable nobs and writes it to the log
- Prints the count as a report and in the log
SELECT ... INTO :name stores the result in a macro variable (as text); NOPRINT suppresses the report and %PUT writes the value to the log. A numeric value may carry leading blanks, so use into :nobs trimmed when you build names or titles from it.
In table t, x is missing in some rows. Which rows does this query return?
proc sql;
select * from t
where x < 10;
quit;- Only rows with a non-missing x below 10
- Rows with x below 10, including those where x is missing
- Only rows where x is missing
- No rows; the query fails because x has missing values
PROC SQL follows SAS rules rather than ANSI NULL logic: a missing value is lower than any number, so it satisfies x < 10. A standard SQL database would exclude the NULLs here. Add and x is not missing to drop them.
What does this code produce?
proc sql;
create table work.big as
select id, amount
from sales
where amount > 1000;
quit;- A printed report only, no data set
- A view named big that is recomputed every time it is used
- A data set work.big with columns id and amount for rows where amount > 1000
- A data set with all columns of sales plus a flag column
CREATE TABLE ... AS SELECT stores the query result as a SAS data set and prints nothing. A plain SELECT without CREATE TABLE prints a report; CREATE VIEW would store the query instead of the data.
Which query lists the regions whose total sales exceed 10000?
- select region, sum(amount) as total from sales where sum(amount) > 10000 group by region;
- select region, sum(amount) as total from sales group by region where total > 10000;
- select region, amount from sales where amount > 10000;
- select region, sum(amount) as total from sales group by region having sum(amount) > 10000;
WHERE filters rows before grouping and cannot contain summary functions; HAVING filters groups after GROUP BY and may use them. WHERE placed after GROUP BY is a syntax error, and filtering individual amounts > 10000 answers a different question.
a has id = 1, 2, 3 and b has id = 2, 3, 4 (one row per id). How many rows does the query return?
proc sql;
select *
from a left join b
on a.id = b.id;
quit;- 3
- 2
- 4
- 9
A LEFT JOIN keeps every row of the left table (ids 1, 2, 3) and fills b's columns with missing values where there is no match (id 1). 2 would be an inner join, 4 a full join, and 9 a Cartesian product without the ON condition.
a has 2 rows with id = 1 and b has 3 rows with id = 1 (no other ids). How many rows does the join return?
proc sql;
select *
from a inner join b
on a.id = b.id;
quit;- 3
- 6
- 2
- 5
An SQL join returns every combination of matching rows: 2 × 3 = 6. A DATA step MERGE with BY id would give only 3 rows, because it pairs rows one-to-one within the group — the key difference between the two methods for many-to-many data.
Descriptive statistics9
What does this one-way table show for each value of sex?
proc freq data=patients;
tables sex;
run;- Mean, Std Dev, Minimum and Maximum
- Only the number of distinct values
- Frequency, Percent, Cumulative Frequency and Cumulative Percent
- Frequency and a chi-square test
A one-way FREQ table lists each distinct value with its count, its percent of the non-missing total and the cumulative versions of both. Means and standard deviations come from PROC MEANS; a chi-square test of association needs a two-way table with the CHISQ option.
In a group*outcome table, group A has 30 'yes' and 10 'no', group B has 20 'yes' and 40 'no' (100 patients). What Row Pct is shown in the cell A / yes?
proc freq data=trial;
tables group*outcome;
run;- 30.00
- 75.00
- 60.00
- 40.00
Row Pct divides the cell count by its row total: 30 / 40 = 75%. 30% is the cell's overall Percent (30 / 100), and 60% is its Col Pct (30 of the 50 'yes' answers).
smoker is missing for 5 of 100 patients. How does a default one-way PROC FREQ table handle them?
proc freq data=patients;
tables smoker;
run;- They are left out of the table and percents, and reported as 'Frequency Missing = 5'
- They appear as a separate row with a percent of 5%
- They are counted in the most frequent category
- The procedure stops with an error
By default missing values are not a level of the table: percents are computed over the 95 non-missing rows and a line below the table states the missing count. The MISSING option on the TABLES statement treats missing as a category (then 5%); MISSPRINT shows it without using it in the percents.
In data set stats, which value of _TYPE_ marks the row with the overall mean over all observations?
proc means data=t noprint;
class region sex;
var income;
output out=stats mean=avg_income;
run;- 1
- 3
- None; only region*sex combinations are written
- 0
Without NWAY the OUTPUT data set contains every combination level of the CLASS variables: _TYPE_ = 0 is the grand total, 1 = by sex alone, 2 = by region alone, 3 = by region and sex (binary digits in CLASS order). NWAY keeps only the highest _TYPE_, 3. _FREQ_ holds the number of rows in each group.
Which statistic is NOT printed by default by PROC MEANS?
- N
- Std Dev
- Maximum
- Median
By default PROC MEANS shows N, Mean, Std Dev, Minimum and Maximum. The median (and other percentiles) must be requested, e.g. proc means data=t n mean median; — or use PROC UNIVARIATE, which reports it by default.
Variable bmi has 10 observations, 2 of them missing. What does PROC MEANS report?
- N = 10, and the sum divided by 10
- N = 10, with missing values counted as 0
- N = 8, and the mean of the 8 non-missing values
- N = 8, and the sum divided by 10
PROC MEANS excludes missing values from every statistic: N counts the non-missing values, and NMISS (on request) reports the 2 missing ones. Treating missing as 0 or dividing by 10 would bias the mean downward.
What is a practical difference between CLASS and BY in PROC MEANS?
- CLASS requires sorted data; BY does not
- Only BY can group by more than one variable
- CLASS works only with character variables
- BY requires the data to be sorted by the grouping variable; CLASS does not
BY processes separate groups one after another, so the data must be sorted (or indexed) by the BY variables, and you get one table per group. CLASS groups internally without sorting and produces a single combined table. Both accept several variables of either type.
Which option makes PROC UNIVARIATE print tests for normality such as Shapiro-Wilk?
proc univariate data=t ______;
var weight;
run;- normal
- plot
- shapiro
- freq
The NORMAL option adds the 'Tests for Normality' table (Shapiro-Wilk, Kolmogorov-Smirnov, Cramer-von Mises, Anderson-Darling). There is no SHAPIRO option; PLOT produces line-printer plots and FREQ a frequency table of the values. A small p-value is evidence against normality.
PROC FREQ with tables group*outcome / chisq; gives a Pearson chi-square p-value of 0.002. What is the correct conclusion?
- group causes the outcome
- The groups have equal outcome proportions
- There is evidence that group and outcome are associated (not independent)
- The table has too few observations for any test
The chi-square test's null hypothesis is independence (equal outcome proportions in all groups). p = 0.002 rejects it, so the variables are associated — which by itself says nothing about causation. Doubts about validity would come from the warning about expected cell counts below 5, not from the p-value.
Statistical procedures9
Which statement tells PROC TTEST which variable defines the two groups being compared?
proc ttest data=study;
______ treatment;
var score;
run;- by
- class
- paired
- model
For a two-sample t test, CLASS names the variable with exactly two levels and VAR the response. BY would run separate analyses for each treatment level instead of comparing them; PAIRED is for paired designs, and MODEL belongs to REG/GLM.
In the default PROC CORR output, what is the second number shown under each Pearson correlation coefficient?
proc corr data=t;
var x y;
run;- The p-value for testing H0: rho = 0
- The standard error of the coefficient
- The number of observations
- The squared correlation
The default table is titled 'Pearson Correlation Coefficients ... Prob > |r| under H0: Rho=0': under each r is the p-value of the test that the population correlation is zero. N is shown in the title, or as a third number when counts differ because of missing values.
Each patient's blood pressure was measured before and after treatment, stored in variables before and after on the same row. Which PROC TTEST statement fits this design?
- class before after;
- var before after;
- by before after;
- paired before*after;
PAIRED performs a paired t test on the differences before − after in each row, which uses the correlation within patients. VAR before after would run two separate one-sample tests against 0, and CLASS needs a single grouping variable — treating the measurements as independent groups ignores the pairing.
Why use PROC GLM rather than PROC REG for a one-way ANOVA of score on a character variable diet with 3 levels?
- PROC REG cannot compute p-values
- GLM does not assume normally distributed errors
- GLM accepts a CLASS statement and builds the dummy variables for diet itself
- PROC REG only works with fewer than 3 predictors
PROC REG accepts only numeric predictors, so a categorical factor would have to be coded into dummy variables by hand. PROC GLM's CLASS statement does that automatically and reports the ANOVA F test. Both fit the same linear model with the same assumptions, including normal errors for the tests.
In this PROC GLM model with unbalanced data, what do the Type III sums of squares test?
proc glm data=t;
class a b;
model y = a b;
run;- Each effect adjusted only for the effects listed before it in MODEL
- Each effect on its own, ignoring all other effects
- Only the a*b interaction
- Each effect adjusted for all other effects in the model, so the order in MODEL does not matter
Type I SS are sequential: each effect is adjusted only for those listed earlier, so with unbalanced data they change when a and b swap places. Type III SS adjust every effect for all the others, which is what is usually reported for unbalanced designs. There is no interaction here, since a*b is not in the model.
PROC REG for model weight = height gives a parameter estimate of 0.9 for height (weight in kg, height in cm). How do you interpret it?
- 90% of the variation in weight is explained by height
- Each additional cm of height is associated with a 0.9 kg higher predicted weight
- The correlation between height and weight is 0.9
- Predicted weight is 0.9 kg when height is 0
A slope estimate is the change in the predicted response per one-unit change in the predictor. The share of variance explained is R-square, the correlation comes from PROC CORR (and is unit-free), and the prediction at height 0 is the intercept.
In PROC TTEST output, the Folded F test for equality of variances has p = 0.001. Which t test row should you report?
- Pooled (equal variances)
- Neither; a t test cannot be used
- The Folded F test itself
- Satterthwaite (unequal variances)
A small Folded F p-value is evidence that the group variances differ, so the pooled test (which assumes equal variances) is inappropriate; the Satterthwaite (Welch) approximation adjusts the degrees of freedom for unequal variances. The F test compares variances, not means.
A simple linear regression (one predictor) has R-square = 0.64 and a negative slope. What is the Pearson correlation between x and y?
- 0.8
- -0.8
- -0.64
- 0.4096
In simple linear regression R-square = r², so |r| = √0.64 = 0.8, and r has the sign of the slope: −0.8. 0.8 ignores the sign, −0.64 forgets the square root, and 0.4096 squares a second time.
A one-way ANOVA in PROC GLM compares 4 groups with 40 observations in total (no missing values). What degrees of freedom are shown for Model and Error?
- Model 3, Error 36
- Model 4, Error 36
- Model 3, Error 39
- Model 4, Error 40
Model DF = number of groups − 1 = 3; Corrected Total DF = n − 1 = 39; Error DF = 39 − 3 = 36 (= n − k). Using 4 for the model forgets that one parameter is the intercept; 39 is the corrected total, not the error.
Macros9
What title is shown?
%let year = 2024;
title 'Sales report &year';- Sales report 2024
- Sales report
- Sales report &year
- Sales report year
Macro references are not resolved inside single quotes, so the text stays literal. Use double quotes — title "Sales report &year"; — when a string should contain the resolved value.
How many characters does the value of &name contain?
%let name = John Smith ;- 10
- 16
- 13
- 4
%LET removes leading and trailing blanks from the value but keeps the blanks inside it, so the value is 'John Smith' — 10 characters. Use %STR( ) quoting when leading or trailing blanks must be kept on purpose.
What does %put write to the log?
%let a = 1 + 2;
%put &a;- 3
- 1 + 2
- a
- An error about a non-numeric value
%LET stores text without evaluating it. Integer arithmetic is done with %eval(&a), which gives 3, and decimal arithmetic with %sysevalf. The expression is computed only if the text later lands in SAS code, e.g. x = &a; in a DATA step.
Macro variable n does not exist before this step. What happens?
data _null_;
call symputx('n', 5);
x = &n;
put x=;
run;- x=5 is written to the log
- x is missing, but no warning appears
- &n cannot be resolved when the step is compiled, so a warning and an error appear
- x=0, because n starts at 0
Macro references are resolved while the code is tokenized, before the DATA step runs. At that point CALL SYMPUTX has not executed yet, so &n gives 'WARNING: Apparent symbolic reference N not resolved' and the leftover &n is a syntax error. The value can be used in code after the step boundary, or within the step via SYMGET('n').
What kind of value does a macro variable hold?
%let n = 10;- A number, because the value consists of digits
- Whatever type a DATA step variable named n has
- Always text, even when it looks like a number
- A reference to a SAS data set
The macro facility is a text processor: %let n = 10; stores the two characters 1 and 0. Arithmetic needs %EVAL or %SYSEVALF, and the text only acts as a number once it lands in SAS code, e.g. x = &n; in a DATA step.
Which line correctly calls this macro to summarise variable amount in data set sales?
%macro summ(ds, var);
proc means data=&ds;
var &var;
run;
%mend summ;- summ(sales, amount);
- %summ(sales, amount)
- %summ ds=sales var=amount;
- call summ('sales', 'amount');
A macro is invoked with % followed by its name and the arguments in parentheses; no semicolon is needed because the generated code has its own. Without % SAS sees an unknown statement, arguments are never passed without parentheses, and CALL starts a DATA step CALL routine.
What does the DATA statement resolve to?
%let lib = mylib;
data &lib..scores;
set raw;
run;- data mylib..scores;
- data mylibscores;
- data &lib.scores;
- data mylib.scores;
A period right after a macro variable reference ends the name and is consumed: &lib. resolves to mylib. The second period is then the library separator, giving mylib.scores. With a single period (&lib.scores) the result would be mylibscores, a one-level WORK name.
What do the two %PUT statements write?
%put %eval(7/2);
%put %sysevalf(7/2);- 3.5 and 3.5
- 4 and 3.5
- 3 and 3.5
- 3 and 3
%EVAL performs integer arithmetic only and truncates the quotient: 7/2 gives 3, not a rounded 4. %SYSEVALF uses floating-point arithmetic and gives 3.5. %eval(7.0/2) would even fail, because 7.0 is not an integer.
What does %put write?
%let city1 = Minsk;
%let city2 = Brest;
%let i = 2;
%put &&city&i;- Brest
- Minsk
- city2
- &city2
The macro processor rescans: on the first pass && becomes & and &i becomes 2, giving &city2; the second pass resolves &city2 to Brest. With a single & (&city&i) SAS would look for a macro variable named city, which does not exist.
Output and ODS9
What is needed after the PROC steps to finish writing report.pdf?
ods pdf file='report.pdf';
proc print data=sales;
run;
proc means data=sales;
run;
______- run;
- ods pdf close;
- quit;
- ods listing;
An ODS destination stays open and collects the output of every procedure until it is closed; ODS PDF CLOSE completes and releases the file. Without it the PDF is incomplete or locked. RUN and QUIT end a step, not a destination, and ODS LISTING opens another destination.
Where does the PUT statement write by default, and what does it write?
data _null_;
x = 5;
put x=;
run;- x=5 to the SAS log
- 5 to the results window
- x=5 to a data set named _null_
- x=5 to the results as a one-row table
Without a FILE statement PUT writes to the log, and the x= form prints the name together with the value. DATA _NULL_ creates no data set at all, which makes it handy for reports, files and debug lines; FILE PRINT would send PUT output to the results instead.
What does this code create?
ods output ParameterEstimates=pe;
proc reg data=t;
model y = x;
run;
quit;- A file named pe with all printed output
- A macro variable pe holding the slope
- A plot of the parameter estimates
- A data set pe containing the parameter estimates table
ODS OUTPUT turns an output object into a SAS data set: pe gets one row per parameter with Estimate, StdErr, tValue, Probt and so on. It is the standard way to reuse procedure results in later steps instead of copying numbers from the printed output.
amount in data set sales has no format. After these steps, what format does amount have in sales?
proc print data=sales;
format amount dollar10.2;
run;
proc means data=sales;
var amount;
run;- DOLLAR10.2, saved in the data set
- None; the format applied only to the PROC PRINT step
- DOLLAR10.2 until the end of the session
- BEST12., because PROC PRINT converts it
A FORMAT statement in a PROC step is temporary and affects only that procedure's output, so PROC MEANS shows amount unformatted. To store a format with the variable use a FORMAT statement in a DATA step or PROC DATASETS (MODIFY).
sales has 100 observations. How many does PROC PRINT show?
proc print data=sales(firstobs=3 obs=5);
run;- 5 (observations 3 to 7)
- 2 (observations 4 and 5)
- 3 (observations 3, 4 and 5)
- 5 (observations 1 to 5)
OBS= is the number of the last observation to process, not a count. With FIRSTOBS=3 and OBS=5 SAS reads observations 3 through 5. Reading OBS=5 as 'five rows' is the common mistake that gives observations 3 to 7.
What does the NOOBS option do?
proc print data=sales noobs;
var region amount;
run;- Suppresses the Obs column with row numbers
- Prints only the variable names, no observations
- Hides observations with missing values
- Prints the number of observations at the end
PROC PRINT shows an 'Obs' column by default; NOOBS removes it. The VAR statement chooses which columns appear and in which order. Hiding rows is done with WHERE, and the N option prints the count.
Which statement writes the names of the output tables (such as ParameterEstimates) produced by a procedure to the log?
- ods select all;
- ods listing close;
- ods trace on;
- proc contents data=_all_;
ODS TRACE ON writes the name, label and path of every output object to the log as procedures run (turn it off with ODS TRACE OFF). Those names are what ODS SELECT, ODS EXCLUDE and ODS OUTPUT need. PROC CONTENTS describes data sets, not output tables.
What is displayed by this code?
ods select Moments;
proc univariate data=t;
var weight;
run;- All UNIVARIATE tables except Moments
- Only the Moments table of PROC UNIVARIATE
- Moments plus all the default tables
- Nothing; ODS SELECT only affects ODS OUTPUT
ODS SELECT keeps only the listed output objects for the next step (the list is reset at the step boundary unless PERSIST is used); ODS EXCLUDE does the opposite. Names such as Moments, BasicMeasures and Quantiles can be found with ODS TRACE.
Which titles appear on output produced after these statements?
title1 'Annual Report';
title2 'Region North';
title3 'Draft';
title2 'Region South';- Annual Report, Region South and Draft
- Region South only
- Annual Report, Region North, Draft and Region South
- Annual Report and Region South
TITLE statements are global and stay in effect until changed. Defining TITLEn replaces that line and clears all higher-numbered titles, so title2 'Region South' also removes title3 'Draft', while TITLE1 is kept. A bare title; clears all titles.
Как проходить тест
- Выберите темы и уровень — лёгкий уровень проверяет определения и задачи в одно действие, средний — стандартные вычисления, сложный — многошаговые задачи и теорию.
- Отвечайте касанием или с клавиатуры: 1–4 или A–D, Enter — следующий вопрос.
- Читайте объяснения — после ошибки разбор открывается сразу, после верного ответа его можно раскрыть кнопкой «Почему».
- Работайте над ошибками — «Повторить ошибки» в конце теста или режим «Только мои ошибки» потом: ответы запоминаются в этом браузере.
Незавершённый тест сохраняется — после перезагрузки страницы можно продолжить с того же вопроса.
Темы теста
- DATA step basics 10
- Reading data 9
- Variables and formats 9
- Conditional logic and loops 9
- Combining data sets 9
- Functions 9
- PROC SQL 9
- Descriptive statistics 9
- Statistical procedures 9
- Macros 9
- Output and ODS 9
Другие тесты
Тест по линейной алгебре160 вопросовТест по дифференциальным уравнениям130 вопросовТест по теории вероятностей и статистике130 вопросовТест по языку R100 вопросовТест по LaTeX100 вопросовТест по системам компьютерной алгебры100 вопросовТест по Fortran120 вопросовТест по языку C100 вопросовТест по COBOL100 вопросовТест по MATLAB100 вопросовТест по PowerBuilder100 вопросовТест по UNIX100 вопросов
