Showing posts with label Interview. Show all posts
Showing posts with label Interview. Show all posts

Thursday, December 30, 2010

SAS Interview Questions

1. What has been your most common programming mistake?
2. What is your favorite programming language and why?
3. What is your favorite operating system? Why?
4. Do you observe any coding standards? What is your opinion of them?
5. What percent of your program code is usually original and what percent copied and modified?
6. Have you ever had to follow SOPs or programming guidelines?
7. Which is worse: not testing your programs or not commenting your programs?
8. Name several ways to achieve efficiency in your program. Explain trade-offs.
9. What other SAS products have you used and consider yourself proficient in using?
10. How do you make use of functions?
11. When looking for contained in a character string of 150 bytes, which function is the best to locate that data: scan, index, or indexc?
12. What is the significance of the ‘OF’ in X=SUM(OF a1-a4, a6, a9);?
13. What do the PUT and INPUT functions do?
14. Which date function advances a date, time or date/time value by a given interval?
15. What do the MOD and INT function do?
16. How might you use MOD and INT on numerics to mimic SUBSTR on character strings?
17. In ARRAY processing, what does the DIM function do?
18. How would you determine the number of missing or nonmissing values in computations?
19. What is the difference between: x=a+b+c+d; and x=SUM(a,b,c,d);?
20. There is a field containing a date. It needs to be displayed in the format “ddmonyy” if it’s before 1975, “dd mon ccyy” if it’s after 1985, and as ‘Disco Years’ if it’s between 1975 and 1985. How would you accomplish this in data step code? Using only PROC FORMAT.
21. In the following DATA step, what is needed for ‘fraction’ to print to the log? data _null_; x=1/3; if x=.3333 then put ‘fraction’; run;
22. What is the difference between calculating the ‘mean’ using the mean function and PROC MEANS?
23. Have you ever used “Proc Merge”? (be prepared for surprising answers..)
24. If you were given several SAS data sets you were unfamiliar with, how would you find out the variable names and formats of each dataset?
25. What SAS PROCs have you used and consider yourself proficient in using?
26. How would you keep SAS from overlaying the a SAS set with its sorted version?
27. In PROC PRINT, can you print only variables that begin with the letter “A”?
28. What are some differences between PROC SUMMARY and PROC MEANS?
29. Code the tables statement for a single-level (most common) frequency.
30. Code the tables statement to produce a multi-level frequency.
31. Name the option to produce a frequency line items rather that a table.
32. Produce output from a frequency. Restrict the printing of the table.
33. Code a PROC MEANS that shows both summed and averaged output of the data.
34. Code the option that will allow MEANS to include missing numeric data to be included in the report.
35. Code the MEANS to produce output to be used later.
36. Do you use PROC REPORT or PROC TABULATE? Which do you prefer? Explain.
37. What happens in a one-on-one merge? When would you use one?
38. How would you combine 3 or more tables with different structures?
39. What is a problem with merging two data sets that have variables with the same name but different data?
40. When would you choose to MERGE two data sets together and when would you SET two data sets?
41. Which data set is the controlling data set in the MERGE statement?
42. How do the IN= variables improve the capability of a MERGE?
43. Explain the message ‘MERGE HAS ONE OR MORE DATASETS WITH REPEATS OF BY VARIABLES”.
44. How would you generate 1000 observations from a normal distribution with a mean of 50 and standard deviation of 20. How would you use PROC CHART to look at the distribution? Describe the shape of the distribution.
45. How do you generate random samples?
46. What is the purpose of the statement DATA _NULL_ ;?
47. What is the pound sign used for in the DATA _NULL_?
48. What would you use the trailing @ sign for?
49. For what purpose(s) would you use the RETURN statement?
50. How would you determine how far down on a page you have printed in order to print out footnotes?
51. What is the purpose of using the N=PS option?
52. What system options would you use to help debug a macro?
53. Describe how you would create a macro variable.
54. How do you identify a macro variable?
55. How do you define the end of a macro?
56. How do you assign a macro variable to a SAS variable?
57. For what purposes have you used SAS macros?
58. What is the difference between %LOCAL and %GLOBAL?
59. How long can a macro variable be? A token?
60. If you use a SYMPUT in a DATA step, when and where can you use the macro variable?
61. What do you code to create a macro? End one?
62. Describe how you would pass data to a macro.
63. You have five data sets that need to be processed identically; how would you simplify that processing with a macro?
64. How would you code a macro statement to produce information on the SAS log? This statement can be coded anywhere.
65. How do you add a number to a macro variable?
66. If you need the value of a variable rather than the variable itself, what would you use to load the value to a macro variable?
67. Can you execute a macro within a macro? Describe.
68. Can you a macro within another macro? If so, how would SAS know where the current macro ended and the new one began?
69. How are parameters passed to a macro?
Read more...

Base SAS Interview Questions Part 3

Under what circumstances would you code a SELECT construct instead of IF statements?

A: I think Select statement is used when you are using one condition to compare with several conditions like…….
Data exam;
Set exam;
select (pass);
when Physics gt 60;
when math gt 100;
when English eq 50;
otherwise fail;
run;

What is the one statement to set the criteria of data that can be coded in any step?
A) Options statement.

What is the effect of the OPTIONS statement ERRORS=1?

A) The –ERROR- variable ha a value of 1 if there is an error in the data for that observation and 0 if it is not.

What's the difference between VAR A1 - A4 and VAR A1 -- A4?

What do the SAS log messages "numeric values have been converted to character" mean? What are the implications?

A) It implies that automatic conversion took place to make character functions possible.

Why is a STOP statement needed for the POINT= option on a SET statement?
A) Because POINT= reads only the specified observations, SAS cannot detect an end-of-file condition as it would if the file were being read sequentially.

How do you control the number of observations and/or variables read or written?

A) FIRSTOBS and OBS option

Approximately what date is represented by the SAS date value of 730?
A) 31st December 1961

Identify statements whose placement in the DATA step is critical.
A) INPUT, DATA and RUN…

Does SAS 'Translate' (compile) or does it 'Interpret'? Explain.
A) Compile

What does the RUN statement do?
A) When SAS editor looks at Run it starts compiling the data or proc step, if you have more than one data step or proc step or if you have a proc step. Following the data step then you can avoid the usage of the run statement.

Why is SAS considered self-documenting?
A) SAS is considered self documenting because during the compilation time it creates and stores all the information about the data set like the time and date of the data set creation later No. of the variables later labels all that kind of info inside the dataset and you can look at that info using proc contents procedure.

What are some good SAS programming practices for processing very large data sets?
A) Sort them once, can use firstobs = and obs = ,

What is the different between functions and PROCs that calculate thesame simple descriptive statistics?
A) Functions can used inside the data step and on the same data set but with proc's you can create a new data sets to output the results. May be more ...........

If you were told to create many records from one record, show how you would do this using arrays and with PROC TRANSPOSE?
A) I would use TRANSPOSE if the variables are less use arrays if the var are more ................. depends

What is a method for assigning first.VAR and last.VAR to the BY groupvariable on unsorted data?
A) In unsorted data you can't use First. or Last.

How do you debug and test your SAS programs?
A) First thing is look into Log for errors or warning or NOTE in some cases or use the debugger in SAS data step.

What other SAS features do you use for error trapping and datavalidation?
A) Check the Log and for data validation things like Proc Freq, Proc means or some times proc print to look how the data looks like ........

How would you combine 3 or more tables with different structures?
A) I think sort them with common variables and use merge statement. I am not sure what you mean different structures.


Other questions:

What areas of SAS are you most interested in?
A) BASE, STAT, GRAPH, ETSBriefly

Describe 5 ways to do a "table lookup" in SAS.
A) Match Merging, Direct Access, Format Tables, Arrays, PROC SQL

What versions of SAS have you used (on which platforms)?
A) SAS 9.1.3,9.0, 8.2 in Windows and UNIX, SAS 7 and 6.12

What are some good SAS programming practices for processing very large data sets?
A) Sampling method using OBS option or subsetting, commenting the Lines, Use Data Null

What are some problems you might encounter in processing missing values? In Data steps? Arithmetic? Comparisons? Functions? Classifying data?
A) The result of any operation with missing value will result in missing value. Most SAS statistical procedures exclude observations with any missing variable values from an analysis.

How would you create a data set with 1 observation and 30 variables from a data set with 30 observations and 1 variable?
A) Using PROC TRANSPOSE

What is the different between functions and PROCs that calculate the same simple descriptive statistics?
A) Proc can be used with wider scope and the results can be sent to a different dataset. Functions usually affect the existing datasets.

If you were told to create many records from one record, show how you would do this using array and with PROC TRANSPOSE?

A) Declare array for number of variables in the record and then used Do loop Proc Transpose with VAR statement

What are _numeric_ and _character_ and what do they do?
A) Will either read or writes all numeric and character variables in dataset.

How would you create multiple observations from a single observation?
A) Using double Trailing @@

For what purpose would you use the RETAIN statement?
A) The retain statement is used to hold the values of variables across iterations of the data step. Normally, all variables in the data step are set to missing at the start of each iteration of the data step.What is the order of evaluation of the comparison operators: + - * / ** ()?A) (), **, *, /, +, -

How could you generate test data with no input data?
A) Using Data Null and put statement

How do you debug and test your SAS programs?
A) Using Obs=0 and systems options to trace the program execution in log.

What can you learn from the SAS log when debugging?
A) It will display the execution of whole program and the logic. It will also display the error with line number so that you can and edit the program.

What is the purpose of _error_?
A) It has only to values, which are 1 for error and 0 for no error.

How can you put a "trace" in your program?
A) By using ODS TRACE ON

How does SAS handle missing values in: assignment statements, functions, a merge, an update, sort order, formats, PROCs?
A) Missing values will be assigned as missing in Assignment statement. Sort order treats missing as second smallest followed by underscore.

How do you test for missing values?
A) Using Subset functions like IF then Else, Where and Select.

How are numeric and character missing values represented internally?
A) Character as Blank or “ and Numeric as.

Which date functions advances a date time or date/time value by a given interval?
A) INTNX.

In the flow of DATA step processing, what is the first action in a typical DATA Step?
A) When you submit a DATA step, SAS processes the DATA step and then creates a new SAS data set.( creation of input buffer and PDV)
Compilation Phase
Execution Phase

What are SAS/ACCESS and SAS/CONNECT?
A) SAS/Access only process through the databases like Oracle, SQL-server, Ms-Access etc. SAS/Connect only use Server connection.

What is the one statement to set the criteria of data that can be coded in any step?
A) OPTIONS Statement, Label statement, Keep / Drop statements.

What is the purpose of using the N=PS option?
A) The N=PS option creates a buffer in memory which is large enough to store PAGESIZE (PS) lines and enables a page to be formatted randomly prior to it being printed.

What are the scrubbing procedures in SAS?
A) Proc Sort with nodupkey option, because it will eliminate the duplicate values.

What are the new features included in the new version of SAS i.e., SAS9.1.3?
A) The main advantage of version 9 is faster execution of applications and centralized access of data and support.

There are lots of changes has been made in the version 9 when we compared with the version 8. The following are the few:SAS version 9 supports Formats longer than 8 bytes & is not possible with version 8.
Length for Numeric format allowed in version 9 is 32 where as 8 in version 8.
Length for Character names in version 9 is 31 where as in version 8 is 32.
Length for numeric informat in version 9 is 31, 8 in version 8.
Length for character names is 30, 32 in version 8.3 new informats are available in version 9 to convert various date, time and datetime forms of data into a SAS date or SAS time.

·ANYDTDTEW. - Converts to a SAS date value ·ANYDTTMEW. - Converts to a SAS time value. ·ANYDTDTMW. -Converts to a SAS datetime value.CALL SYMPUTX Macro statement is added in the version 9 which creates a macro variable at execution time in the data step by ·

Trimming trailing blanks · Automatically converting numeric value to character.
New ODS option (COLUMN OPTION) is included to create a multiple columns in the output.

WHAT DIFFERRENCE DID YOU FIND AMONG VERSION 6 8 AND 9 OF SAS.
The SAS 9

A) Architecture is fundamentally different from any prior version of SAS. In the SAS 9 architecture, SAS relies on a new component, the Metadata Server, to provide an information layer between the programs and the data they access. Metadata, such as security permissions for SAS libraries and where the various SAS servers are running, are maintained in a common repository.

What has been your most common programming mistake?
A) Missing semicolon and not checking log after submitting program,
Not using debugging techniques and not using Fsview option vigorously.

Name several ways to achieve efficiency in your program.
Efficiency and performance strategies can be classified into 5 different areas.
·CPU time
·Data Storage
· Elapsed time
· Input/Output
· Memory CPU Time and Elapsed Time- Base line measurements

Few Examples for efficiency violations:
Retaining unwanted datasets Not sub setting early to eliminate unwanted records.
Efficiency improving techniques:
A)
Using KEEP and DROP statements to retain necessary variables. Use macros for reducing the code.
Using IF-THEN/ELSE statements to process data programming.
Use SQL procedure to reduce number of programming steps.
Using of length statements to reduce the variable size for reducing the Data storage.
Use of Data _NULL_ steps for processing null data sets for Data storage.

What other SAS products have you used and consider yourself proficient in using?
B) A) Data _NULL_ statement, Proc Means, Proc Report, Proc tabulate, Proc freq and Proc print, Proc Univariate etc.

What is the significance of the 'OF' in X=SUM (OF a1-a4, a6, a9);
A) If don’t use the OF function it might not be interpreted as we expect. For example the function above calculates the sum of a1 minus a4 plus a6 and a9 and not the whole sum of a1 to a4 & a6 and a9. It is true for mean option also.

What do the PUT and INPUT functions do?
A) INPUT function converts character data values to numeric values.
PUT function converts numeric values to character values.EX: for INPUT: INPUT (source, informat)
For PUT: PUT (source, format)
Note that INPUT function requires INFORMAT and PUT function requires FORMAT.
If we omit the INPUT or the PUT function during the data conversion, SAS will detect the mismatched variables and will try an automatic character-to-numeric or numeric-to-character conversion. But sometimes this doesn’t work because $ sign prevents such conversion. Therefore it is always advisable to include INPUT and PUT functions in your programs when conversions occur.

Introduction to SAS Informats and Formats

Which date function advances a date, time or datetime value by a given interval?
INTNX:
INTNX function advances a date, time, or datetime value by a given interval, and returns a date, time, or datetime value. Ex: INTNX(interval,start-from,number-of-increments,alignment)

INTCK: INTCK(interval,start-of-period,end-of-period) is an interval functioncounts the number of intervals between two give SAS dates, Time and/or datetime.

DATETIME () returns the current date and time of day.

DATDIF (sdate,edate,basis): returns the number of days between two dates.

What do the MOD and INT function do? What do the PAD and DIM functions do? MOD:
A) Modulo is a constant or numeric variable, the function returns the reminder after numeric value divided by modulo.

INT: It returns the integer portion of a numeric value truncating the decimal portion.

PAD: it pads each record with blanks so that all data lines have the same length. It is used in the INFILE statement. It is useful only when missing data occurs at the end of the record.

CATX: concatenate character strings, removes leading and trailing blanks and inserts separators.

SCAN: it returns a specified word from a character value. Scan function assigns a length of 200 to each target variable.

SUBSTR: extracts a sub string and replaces character values.Extraction of a substring: Middleinitial=substr(middlename,1,1); Replacing character values: substr (phone,1,3)=’433’; If SUBSTR function is on the left side of a statement, the function replaces the contents of the character variable.

TRIM: trims the trailing blanks from the character values.

SCAN vs. SUBSTR: SCAN extracts words within a value that is marked by delimiters. SUBSTR extracts a portion of the value by stating the specific location. It is best used when we know the exact position of the sub string to extract from a character value.

How might you use MOD and INT on numeric to mimic SUBSTR on character Strings?
A) The first argument to the MOD function is a numeric, the second is a non-zero numeric; the result is the remainder when the integer quotient of argument-1 is divided by argument-2. The INT function takes only one argument and returns the integer portion of an argument, truncating the decimal portion. Note that the argument can be an expression.
DATA NEW ;
A = 123456 ;
X = INT( A/1000 ) ;
Y = MOD( A, 1000 ) ;
Z = MOD( INT( A/100 ), 100 ) ;
PUT A= X= Y= Z= ;
RUN ;
Result:

A=123456
X=123
Y=456
Z=34

In ARRAY processing, what does the DIM function do?
A) DIM: It is used to return the number of elements in the array. When we use Dim function we would have to re –specify the stop value of an iterative DO statement if u change the dimension of the array.

How would you determine the number of missing or nonmissing values in computations?
A) To determine the number of missing values that are excluded in a computation, use the NMISS function.
data _null_;
m = . ;
y = 4 ;
z = 0 ;
N = N(m , y, z);
NMISS = NMISS (m , y, z);
run;

The above program results in N = 2 (Number of non missing values) and NMISS = 1 (number of missing values).

Do you need to know if there are any missing values?
A) Just use: missing_values=MISSING(field1,field2,field3);
This function simply returns 0 if there aren't any or 1 if there are missing values.If you need to know how many missing values you have then use num_missing=NMISS(field1,field2,field3);

You can also find the number of non-missing values with non_missing=N (field1,field2,field3);

What is the difference between: x=a+b+c+d; and x=SUM (of a, b, c ,d);?
A) Is anyone wondering why you wouldn’t just use total=field1+field2+field3;

First, how do you want missing values handled?
The SUM function returns the sum of non-missing values. If you choose addition, you will get a missing value for the result if any of the fields are missing. Which one is appropriate depends upon your needs.However, there is an advantage to use the SUM function even if you want the results to be missing. If you have more than a couple fields, you can often use shortcuts in writing the field names If your fields are not numbered sequentially but are stored in the program data vector together then you can use: total=SUM(of fielda--zfield); Just make sure you remember the “of” and the double dashes or your code will run but you won’t get your intended results. Mean is another function where the function will calculate differently than the writing out the formula if you have missing values.There is a field containing a date. It needs to be displayed in the format "ddmonyy" if it's before 1975, "dd mon ccyy" if it's after 1985, and as 'Disco Years' if it's between 1975 and 1985.

How would you accomplish this in data step code?
Using only PROC FORMAT.
data new ;input date ddmmyy10.;cards;
01/05/1955
01/09/1970
01/12/1975
19/10/1979
25/10/1982
10/10/1988
27/12/1991
;
run;proc format ;value dat low-'01jan1975'd=ddmmyy10.'01jan1975'd-'01JAN1985'd="Disco Years"'
01JAN1985'd-high=
date9.;run;proc print;
format date dat. ;run;

In the following DATA step, what is needed for 'fraction' to print to the log?
data _null_;
x=1/3;
if x=.3333 then put 'fraction';
run;

What is the difference between calculating the 'mean' using the mean function and PROC MEANS?
A) By default Proc Means calculate the summary statistics like N, Mean, Std deviation, Minimum and maximum, Where as Mean function compute only the mean values.

What are some differences between PROC SUMMARY and PROC MEANS?
Proc means by default give you the output in the output window and you can stop this by the option NOPRINT and can take the output in the separate file by the statement OUTPUTOUT= , But, proc summary doesn't give the default output, we have to explicitly give the output statement and then print the data by giving PRINT option to see the result.

What is a problem with merging two data sets that have variables with the same name but different data?
A) Understanding the basic algorithm of MERGE will help you understand how the stepProcesses. There are still a few common scenarios whose results sometimes catch users off guard. Here are a few of the most frequent 'gotchas':

1- BY variables has different lengthsIt is possible to perform a MERGE when the lengths of the BY variables are different,But if the data set with the shorter version is listed first on the MERGE statement, theShorter length will be used for the length of the BY variable during the merge. Due to this shorter length, truncation occurs and unintended combinations could result.In Version 8, a warning is issued to point out this data integrity risk. The warning will be issued regardless of which data set is listed first:WARNING: Multiple lengths were specified for the BY variable name by input data sets.This may cause unexpected results. Truncation can be avoided by naming the data set with the longest length for the BY variable first on the MERGE statement, but the warning message is still issued. To prevent the warning, ensure the BY variables have the same length prior to combining them in the MERGE step with PROC CONTENTS. You can change the variable length with either a LENGTH statement in the merge DATA step prior to the MERGE statement, or by recreating the data sets to have identical lengths for the BY variables.Note: When doing MERGE we should not have MERGE and IF-THEN statement in one data step if the IF-THEN statement involves two variables that come from two different merging data sets. If it is not completely clear when MERGE and IF-THEN can be used in one data step and when it should not be, then it is best to simply always separate them in different data step. By following the above recommendation, it will ensure an error-free merge result.

Which data set is the controlling data set in the MERGE statement?
A) Dataset having the less number of observations control the data set in the merge statement.

How do the IN= variables improve the capability of a MERGE?
A) The IN=variablesWhat if you want to keep in the output data set of a merge only the matches (only those observations to which both input data sets contribute)? SAS will set up for you special temporary variables, called the "IN=" variables, so that you can do this and more. Here's what you have to do: signal to SAS on the MERGE statement that you need the IN= variables for the input data set(s) use the IN= variables in the data step appropriately, So to keep only the matches in the match-merge above, ask for the IN= variables and use them:data three;merge one(in=x) two(in=y); /* x & y are your choices of names */by id; /* for the IN= variables for data */if x=1 and y=1; /* sets one and two respectively */run;

What techniques and/or PROCs do you use for tables?
A) Proc Freq, Proc univariate, Proc Tabulate & Proc Report.

Do you prefer PROC REPORT or PROC TABULATE? Why?
A) I prefer to use Proc report until I have to create cross tabulation tables, because, It gives me so many options to modify the look up of my table, (ex: Width option, by this we can change the width of each column in the table) Where as Proc tabulate unable to produce some of the things in my table. Ex: tabulate doesn’t produce n (%) in the desirable format.

How experienced are you with customized reporting and use of DATA _NULL_ features?
A) I have very good experience in creating customized reports as well as with Data _NULL_ step. It’s a Data step that generates a report without creating the dataset there by development time can be saved. The other advantages of Data NULL is when we submit, if there is any compilation error is there in the statement which can be detected and written to the log there by error can be detected by checking the log after submitting it. It is also used to create the macro variables in the data set.

What is the difference between nodup and nodupkey options?
A) NODUP compares all the variables in our dataset while NODUPKEY compares just the BY variables.

What is the difference between compiler and interpreter?
Give any one example (software product) that act as an interpreter?
A) Both are similar as they achieve similar purposes, but inherently different as to how they achieve that purpose. The interpreter translates instructions one at a time, and then executes those instructions immediately. Compiled code takes programs (source) written in SAS programming language, and then ultimately translates it into object code or machine language. Compiled code does the work much more efficiently, because it produces a complete machine language program, which can then be executed.

Code the table’s statement for a single level frequency?
A) Proc freq data=lib.dataset;
table var;*here you can mention single variable of multiple variables seperated by space to get single frequency;
run;

What is the main difference between rename and label?
A) 1. Label is global and rename is local i.e., label statement can be used either in proc or data step where as rename should be used only in data step. 2. If we rename a variable, old name will be lost but if we label a variable its short name (old name) exists along with its descriptive name.

What is Enterprise Guide? What is the use of it?
A) It is an approach to import text files with SAS (It comes free with Base SAS version 9.0)

What other SAS features do you use for error trapping and data validation?
What are the validation tools in SAS?
A) For dataset: Data set name/debugData set: name/stmtchk
For macros: Options:mprint mlogic symbolgen.

How can you put a "trace" in your program?
A) ODS Trace ON, ODS Trace OFF the trace records.

How would you code a merge that will keep only the observations that have matches from both data sets?


 Using "IN" variable option. Look at the following example.
data three;
merge one(in=x) two(in=y);
by id;
if x=1 and y=1;
run;
*or;
data three;
merge one(in=x) two(in=y);
by id;
if x and y;
run;


What are input dataset and output dataset options?
A) Input data set options are obs, firstobs, where, in output data set options compress, reuse.Both input and output dataset options include keep, drop, rename, obs, first obs.

How can u create zero observation dataset?
A) Creating a data set by using the like clause.ex: proc sql;create table latha.emp like oracle.emp;quit;In this the like clause triggers the existing table structure to be copied to the new table. using this method result in the creation of an empty table.

Have you ever-linked SAS code, If so, describe the link and any required statements used to either process the code or the step itself?

A) In the editor window we write%include 'path of the sas file';run;if it is with non-windowing environment no need to give run statement.

How can u import .CSV file in to SAS? tell Syntax?
A) To create CSV file, we have to open notepad, then, declare the variables.
proc import datafile='E:\age.csv'
out=test dbms=csv replace;
getnames=yes;
run;

What is the use of Proc SQl?
A) PROC SQL is a powerful tool in SAS, which combines the functionality of data and proc steps. PROC SQL can sort, summarize, subset, join (merge), and concatenate datasets, create new variables, and print the results or create a new dataset all in one step! PROC SQL uses fewer resources when compard to that of data and proc steps. To join files in PROC SQL it does not require to sort the data prior to merging, which is must, is data merge.

What is SAS GRAPH?
A) SAS/GRAPH software creates and delivers accurate, high-impact visuals that enable decision makers to gain a quick understanding of critical business issues.

Why is a STOP statement needed for the point=option on a SET statement?
A) When you use the POINT= option, you must include a STOP statement to stop DATA step processing, programming logic that checks for an invalid value of the POINT= variable, or Both. Because POINT= reads only those observations that are specified in the DO statement, SAScannot read an end-of-file indicator as it would if the file were being read sequentially. Because reading an end-of-file indicator ends a DATA step automatically, failure to substitute another means of ending the DATA step when you use POINT= can cause the DATA step to go into a continuous loop.

What is the difference between nodup and nodupkey options?
Read more...

Base SAS Interview Questions Part 2

What SAS statements would you code to read an external raw data file to a DATA step?
We use SAS statements –
FILENAME – to specify the location of the file
INFILE - Identifies an external file to read with an INPUT statement
INPUT – to specify the variables that the data is identified with.


How do you read in the variables that you need?
Using Input statement with column /line pointers, informats and length specifiers.

Are you familiar with special input delimiters? How are they used?
DLM, DSD are the special input delimiters…

DELIMITER= delimiter(s)
specifies an alternate delimiter (other than a blank) to be used for LIST input
DSD (delimiter-sensitive data)
specifies that when data values are enclosed in quotation marks, delimiters within the value be treated as character data. The DSD option changes how SAS treats delimiters when you use LIST input and sets the default delimiter to a comma. When you specify DSD, SAS treats two consecutive delimiters as a missing value and removes quotation marks from character values
http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000146932.htm#a000177189

If reading a variable length file with fixed input, how would you prevent SAS from reading the next record if the last variable didn't have a value?
Options MISSOVER and TRUNCOVER options..
MISSOVER
prevents an INPUT statement from reading a new input data record if it does not find values in the current input line for all the variables in the statement. When an INPUT statement reaches the end of the current input data record, variables without any values assigned are set to missing.
TRUNCOVER
overrides the default behavior of the INPUT statement when an input data record is shorter than the INPUT statement expects. By default, the INPUT statement automatically reads the next input data record. TRUNCOVER enables you to read variable-length records when some records are shorter than the INPUT statement expects. Variables without any values assigned are set to missing.
http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000146932.htm#a000177189

What is the difference between an informat and a format? Name three informats or formats.

INFORMAT Statement - Associates informats with variables
It’s basically used in an input / SQL create table statements to read external file raw data or data that is not in a SAS format.

http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000178244.htm

eg: commaw. datew. Wordatew. dollarw. $varyinglengthw.
FORMAT Statement Associates formats with variables

It’s basically used in a datastep format / SQL select / Procedure format statements to output SAS data to a file/report etc.

Formats can look-like informats but are differentiated as to which statement they are used in…

eg. Datew., Worddatew., mmddyyw.

http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000178212.htm


Name and describe three SAS functions that you have used, if any?

The most common functions that would be used are-
Conversion functions - Input / Put / int / ceil / floor
Character functions - Scan / substr / index / Left / trim / compress / cat / catx / upcase,lowcase
Arithmetic functions - Sum / abs /
Attribute info functions – Attrn / length
Dataset – open / close / exist
Directory - dexist / dopen / dclose / dcreate / dinfo
File functions – fexist / fopen/ filename / fileref
SQL functions – coalesce / count / sum/ mean
Date functions – date / today / datdif / datepart / datetime / intck / mdy
Array functions – dim



How would you code the criteria to restrict the output to be produced?
In view of in-sufficient clarity as to what the interviewer refers to –

Global statement – options obs=;
Dataset options – obs=
Proc SQL - NOPRINT option for reporting / inobs= , outobs= for SQL select
Proc datasets – NOLIST option


What is the purpose of the trailing @ and the @@? How would you use them?

Line-hold specifiers keep the pointer on the current input record when
• a data record is read by more than one INPUT statement (trailing @)
• one input line has values for more than one observation (double trailing @)
• a record needs to be reread on the next iteration of the DATA step (double trailing @).
Use a single trailing @ to allow the next INPUT statement to read from the same record. Use a double trailing @ to hold a record for the next INPUT statement across iterations of the DATA step.
Normally, each INPUT statement in a DATA step reads a new data record into the input buffer. When you use a trailing @, the following occurs:
• The pointer position does not change.
• No new record is read into the input buffer.
• The next INPUT statement for the same iteration of the DATA step continues to read the same record rather than a new one.
SAS releases a record held by a trailing @ when
• a null INPUT statement executes:
input;
• an INPUT statement without a trailing @ executes
• the next iteration of the DATA step begins.
Normally, when you use a double trailing @ (@@), the INPUT statement for the next iteration of the DATA step continues to read the same record. SAS releases the record that is held by a double trailing @
• immediately if the pointer moves past the end of the input record
• immediately if a null INPUT statement executes:
input;
• when the next iteration of the DATA step begins if an INPUT statement with a single trailing @ executes later in the DATA step:
input @;

A record held by the double trailing at sign (@@) is not released until

• the input pointer moves past the end of the record. Then the input pointer moves down to the next record. >----+----10--V+-
102 92 78 103
84 23 36 75



• an INPUT statement without a line-hold specifier executes. input ID $4. @@;
.
.
input Department 5.;

• enables the next INPUT statement to read from the same record
• releases the current record when a subsequent INPUT statement executes without a line-hold specifier.

Unlike the @@, the single @ also releases a record when control returns to the top of the DATA step for the next iteration.


data perm.sales97;
infile data97 missover;
input ID $4. @;
do Quarter=1 to 4;
input Sales : comma. @;
output;
end;
run;

Raw Data File Data97
>----V----10---+----20---+----30---+----40
0734 1,323.34 2,472.85 3,276.65 5,345.52
0943 1,908.34 2,560.38
1009 2,934.12 3,308.41 4,176.18 7,581.81



data perm.people (drop=type);
infile census;
retain Address;
input type $1. @;
if type='H' then input @3 Address $15.;
if type='P';
input @3 Name $10. @13 Age 3. @15 Gender $1.;
run;



>V---+----10---+----
H 321 S. MAIN ST
P MARY E 21 F
P
P WILLIAM M 23 M
SUSAN K 3 F



data perm.residnts;
infile census;
retain Address;
input type $1. @;
if type='H' then do;
if _n_ > 1 then output;
Total=0;
input Address $ 3-17;
end;
else if type='P' then total+1; >----+----10---+----20
H
P
P
P
H
P
P
P
P
P
H
P
P
H
P
P 321 S. MAIN ST
MARY E 21 F
WILLIAM M 23 M
SUSAN K 3 F
324 S. MAIN ST
THOMAS H 79 M
WALTER S 46 M
ALICE A 42 F
MARYANN A 20 F
JOHN S 16 M
325A S. MAIN ST
JAMES L 34 M
LIZA A 31 F
325B S. MAIN ST
MARGO K 27 F
WILLIAM R 27 M
P ROBERT W 1 M





Under what circumstances would you code a SELECT construct instead of IF statements?
The SELECT statement begins a SELECT group. SELECT groups contain WHEN statements that identify SAS statements that are executed when a particular condition is true. Use at least one WHEN statement in a SELECT group. An optional OTHERWISE statement specifies a statement to be executed if no WHEN condition is met. An END statement ends a SELECT group.
Null statements that are used in WHEN statements cause SAS to recognize a condition as true without taking further action. Null statements that are used in OTHERWISE statements prevent SAS from issuing an error message when all WHEN conditions are false.
Using Select-When improves processing efficiency and understandability in programs that needed to check a series of conditions for the same variable.
Use IF-THEN/ELSE statements for programs with few statements.
Using a subsetting IF statement without a THEN clause could be dangerous because it would process only those records that meet the condition specified in the IF clause.
http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000201966.htm

What statement you code to tell SAS that it is to write to an external file?

FILENAME / FILE/ PUT

The FILENAME statement is an optional statement that species the location of the external file.
PUT Statement – Writes the variable values to the external file.

The FILE statement specifies the current output file for PUT statements in the DATA step.
When multiple FILE statements are present, the PUT statement builds and writes output lines to the file that was specified in the most recent FILE statement. If no FILE statement was specified, the PUT statement writes to the SAS log. The specified output file must be an external file, not a SAS data library, and it must be a valid access type.

If reading an external file to produce an external file, what is the shortcut to write that record without coding every single variable on the record?

Use the _infile_ option in the put statement

filename some 'c:\cool.dat';
filename cool1 'c:\cool1.dat';
data _null_;
infile some;
input some;
file cool1;
put _infile_;
run;

If you're not wanting any SAS output from a data step, how would you code the data statement to prevent SAS from producing a set?

Data _null_;

_NULL_ - specifies that SAS does not create a data set when it executes the DATA step.

Data _null_ is majorly used in

o creating quick macro variables with call symput routine
eg.
Data _null_;
Set somedata;
Call symput(‘macvar’,dsnvariable);
Run;
o Creating a Custom Report
Eg.
The second DATA step in this program produces a custom report and uses the _NULL_ keyword to execute the DATA step without creating a SAS data set:
data sales; input dept : $10. jan feb mar; datalines; shoes 4344 3555 2666 housewares 3777 4888 7999 appliances 53111 7122 41333 ; data _null_; set sales; qtr1tot=jan+feb+mar; put 'Total Quarterly Sales: ' qtr1tot dollar12.; run;

What is the one statement to set the criteria of data that can be coded in any step?
WHERE statement can sets the criteria for any data set in a datastep or a proc step.

Have you ever linked SAS code? If so, describe the link and any required statements used to either process the code or the step itself.

SAS code could be linked using the GOTO or the Link statement.

GOTO - http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000201949.htm
LINK - http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000201972.htm
The difference between the LINK statement and the GO TO statement is in the action of a subsequent RETURN statement. A RETURN statement after a LINK statement returns execution to the statement that follows LINK. A RETURN statement after a GO TO statement returns execution to the beginning of the DATA step, unless a LINK statement precedes GO TO, in which case execution continues with the first statement after LINK. In addition, a LINK statement is usually used with an explicit RETURN statement, whereas a GO TO statement is often used without a RETURN statement.
When your program executes a group of statements at several points in the program, using the LINK statement simplifies coding and makes program logic easier to follow. If your program executes a group of statements at only one point in the program, using DO-group logic rather than LINK-RETURN logic is simpler.
Goto eg.
data info;
input x;
if 1<=x<=5 then go to add; put x=; add: sumx+x; datalines; 7 6 323 ; Link Eg. data hydro; input type $ depth station $; /* link to label calcu: */ if type ='aluv' then link calcu; date=today(); /* return to top of step */ return; calcu: if station='site_1' then elevatn=6650-depth; else if station='site_2' then elevatn=5500-depth; /* return to date=today(); */ return; datalines; aluv 523 site_1 uppa 234 site_2 aluv 666 site_2 ...more data lines... ;
How would you include common or reuse code to be processed along with your statements?
- Using SAS Macros. - Using a %include statement When looking for data contained in a character string of 150 bytes,
which function is the best to locate that data: scan, index, or indexc?
Index function - Searches a character expression for a string of characters SAS Statements Results a='ABC.DEF (X=Y)'; b='X=Y'; x=index(a,b); put x; 10 For learning purposes The INDEXC function searches for the first occurrence of any individual character that is present within the character string, whereas the INDEX function searches for the first occurrence of the character string as a pattern. b='have a good day'; x=indexc(b,'pleasant','very'); put x; The INDEXW function searches for strings that are words, whereas the INDEX function searches for patterns as separate words or as parts of other words. INDEXC searches for any characters that are present in the excerpts. s='asdf adog dog'; p='dog '; x=indexw(s,p); put x; If you have a data set that contains 100 variables, but you need only five of those,
what is the code to force SAS to use only those variables?
Use KEEP= dataset option (data statement or set statement) or KEEP statement in a datastep. eg. Data fewdata (keep = var10 var11); Set fulldata (Keep= VAR1 VAR2 VAR3 VAR4 VAR5); Keep var6 var7; Run; Code a PROC SORT on a data set containing State, District and County as the primary variables, along with several numeric variables. Proc sort data= Dist_County; By state district city; Run;
How would you delete duplicate observations?
noduprecs option in a Proc Sort. data cricket; input id country $9. score; cards; 1 australia 342 2 somerset 343 1 australia 342 2 somerset 341 ; run; proc sort data = cricket noduprecs; by id; run; Here in the example observation 1 and 3 are duplicate records….so Obs 1 is retained…
How would you delete observations with duplicate keys?
nodupkey option in a Proc Sort. proc sort data = cricket nodupkey; by id; run; In the above example Observation 1/ 3 and 2 / 4 have duplicate key (variable id) values i.e. 1 and 2 respectively…so observations 3 / 4 get deleted…
How would you code a merge that will keep only the observations that have matches from both sets.
data mergeddata; merge one(in=A) two(in=B); By ID; if A and B; run; How would you code a merge that will write the matches of both to one data set, the non-matches from the left-most data. Data one two three; Merge DSN1 (in=A) DSN2 (in=B); By ID; If A and B then output one; If A and not B then output two; If not A and B then output three; Run;
What is the Program Data Vector (PDV)? What are its functions?
PDV is a logical area in memory where SAS builds a data set, one observation at a time. When a program executes, SAS reads data values from the input buffer or creates them by executing SAS language statements. The data values are assigned to the appropriate variables in the program data vector. From here, SAS writes the values to a SAS data set as a single observation. Along with data set variables and computed variables, the PDV contains two automatic variables, _N_ and _ERROR_. The _N_ variable counts the number of times the DATA step begins to iterate. The _ERROR_ variable signals the occurrence of an error caused by the data during execution. The value of _ERROR_ is either 0 (indicating no errors exist), or 1 (indicating that one or more errors have occurred). SAS does not write these variables to the output data set.
Does SAS 'Translate' (compile) or does it 'Interpret'? Explain.
At compile time when a SAS data set is read, what items are created? SAS compiles the code sent to the compiler. When you submit a DATA step for execution, SAS checks the syntax of the SAS statements and compiles them, that is, automatically translates the statements into machine code. In this phase, SAS identifies the type and length of each new variable, and determines whether a type conversion is necessary for each subsequent reference to a variable. During the compile phase, SAS creates the following three items: input buffer is a logical area in memory into which SAS reads each record of raw data when SAS executes an INPUT statement. Note that this buffer is created only when the DATA step reads raw data. (When the DATA step reads a SAS data set, SAS reads the data directly into the program data vector.) program data vector (PDV) is a logical area in memory where SAS builds a data set, one observation at a time. When a program executes, SAS reads data values from the input buffer or creates them by executing SAS language statements. The data values are assigned to the appropriate variables in the program data vector. From here, SAS writes the values to a SAS data set as a single observation. Along with data set variables and computed variables, the PDV contains two automatic variables, _N_ and _ERROR_. The _N_ variable counts the number of times the DATA step begins to iterate. The _ERROR_ variable signals the occurrence of an error caused by the data during execution. The value of _ERROR_ is either 0 (indicating no errors exist), or 1 (indicating that one or more errors have occurred). SAS does not write these variables to the output data set. descriptor information is information that SAS creates and maintains about each SAS data set, including data set attributes and variable attributes. It contains, for example, the name of the data set and its member type, the date and time that the data set was created, and the number, names and data types (character or numeric) of the variables. The Execution Phase By default, a simple DATA step iterates once for each observation that is being created. The flow of action in the Execution Phase of a simple DATA step is described as follows: • The DATA step begins with a DATA statement. Each time the DATA statement executes, a new iteration of the DATA step begins, and the _N_ automatic variable is incremented by 1. • SAS sets the newly created program variables to missing in the program data vector (PDV). • SAS reads a data record from a raw data file into the input buffer, or it reads an observation from a SAS data set directly into the program data vector. You can use an INPUT, MERGE, SET, MODIFY, or UPDATE statement to read a record. • SAS executes any subsequent programming statements for the current record. • At the end of the statements, an output, return, and reset occur automatically. SAS writes an observation to the SAS data set, the system automatically returns to the top of the DATA step, and the values of variables created by INPUT and assignment statements are reset to missing in the program data vector. Note that variables that you read with a SET, MERGE, MODIFY, or UPDATE statement are not reset to missing here. • SAS counts iteration, reads the next record or observation, and executes the subsequent programming statements for the current observation. • The DATA step terminates when SAS encounters the end-of-file in a SAS data set or a raw data file. All the variables are assigned missing values (Blank for character, . for numeric values) Name statements that are recognized at compile time only? drop, keep, rename, label, format, informat, attrib, where, by, retain, length, array Name statements that are execution only. INFILE, INPUT, Output, Call routines Identify statements whose placement in the DATA step is critical. DATA, INPUT, RUN, CARDS ,INFILE,WHERE,LABEL,SELECT,INFORMAT,FORMAT Name statements that function at both compile and execution time. options, title, footnote In the flow of DATA step processing, what is the first action in a typical DATA Step? The DATA step begins with a DATA statement. Each time the DATA statement executes, a new iteration of the DATA step begins, and the _N_ automatic variable is incremented by 1. What is _n_? The _N_ variable counts the number of times the DATA step begins to iterate.
It is one of the Automatic data step (and not proc’s) variables (the other one being _ERROR_) that SAS provides in a PDV. It should be noted that _n_ does not necessarily equal the observation number in a dataset.

How do I convert a numeric variable to a character variable?Practically, the data type of a variable cannot be changed in one data step, but the data values could…One should create a new variable with data type character and assign the values of the numeric variable with a PUT function, drop the numeric variable, and rename the character variable to the numeric variable name. Note: You would receive a warning saying that the variable has already been defined as numeric. Eg.
http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000199354.htm#a000226452

How do I convert a character variable to a numeric variable?Practically, the data type of a variable cannot be changed in one data step, but the data values could…One should create a new variable with data type numeric and assign the values of the character variable with a INPUT function, drop the character variable, and rename the numeric variable to the character variable name. Note: You would receive a warning saying that the variable has already been defined as character.
http://support.sas.com/onlinedoc/913/getDoc/en/lrdict.hlp/a000180357.htm
Read more...

Base SAS Interview Questions Part 1

What SAS statements would you code to read an external raw data file to a DATA step?INFILE statement.

· How do you read in the variables that you need?Using Input statement with the column pointers like @5/12-17 etc.

· Are you familiar with special input delimiters? How are they used?DLM and DSD are the delimiters that I’ve used. They should be included in the infile statement. Comma separated values files or CSV files are a common type of file that can be used to read with the DSD option. DSD option treats two delimiters in a row as MISSING value.

DSD also ignores the delimiters enclosed in quotation marks.

· If reading a variable length file with fixed input, how would you prevent SAS from reading the next record if the last variable didn't have a value?By using the option MISSOVER in the infile statement.If the input of some data lines are shorter than others then we use TRUNCOVER option in the infile statement.

· What is the difference between an informat and a format? Name three informats or formats.
Informats read the data. Format is to write the data.
Informats: comma. dollar. date.
Formats can be same as informatsInformats: MMDDYYw. DATEw. TIMEw. , PERCENTw,Formats: WORDIATE18., weekdatew.

· Name and describe three SAS functions that you have used, if any?
LENGTH: returns the length of an argument not counting the trailing blanks.(missing values have a length of
1)Ex:

a=’my cat’;
x=LENGTH(a);

Result: x=6…

SUBSTR: SUBSTR(arg,position,n) extracts a substring from an argument starting at ‘position’ for ‘n’ characters or until end if no ‘n’.
Ex:

data dsn;
A=’(916)734-6241’;
X=SUBSTR(a,2,3);
RESULT: x=’916’ ;
run;
TRIM: removes trailing blanks from character expression.
Ex: a=’my ‘; b=’cat’;X= TRIM(a)(b); RESULT: x=’mycat’.

SUM: sum of non missing values.Ex: x=Sum(3,5,1); result: x=9.0

INT: Returns the integer portion of the argument.

· How would you code the criteria to restrict the output to be produced?
Use NOPRINT option.

· What is the purpose of the trailing @ and the @@? How would you use them?@ holds the value past the data step.@@ holds the value till a input statement or end of the line.

Double trailing @@: When you have multiple observations per line of raw data, we should use double trailing signs (@@) at the end of the INPUT statement. The line hold specifies like a stop sign telling SAS, “stop, hold that line of raw data”.
ex:
data dsn;

input sex $ days;
cards;
F 53
F 56
F 60
F 60
F 78
F 87
F 102
F 117
F 134
F 160
F 277
M 46
M 52
M 58
M 59
M 77
M 78
M 80
M 81
M 84
M 103
M 114
M 115
M 133
M 134
M 175
M 175
;
run;

The above program can be changed to make the program shorter using @@ ....

data dsn;
input sex $ days @@;
cards;
F 53 F 56 F 60 F 60 F 78 F 87 F 102 F 117 F 134 F 160 F 277M 46 M 52 M 58 M 59 M 77 M 78 M 80 M 81 M 84 M 103 M 114M 115 M 133 M 134 M 175 M 175
;
run;

Trailing @: By using @ without specifying a column, it is as if you are telling SAS,” stay tuned for more information. Don’t touch that dial”. SAS will hold the line of data until it reaches either the end of the data step or an INPUT statement that does not end with the trailing.

· Under what circumstances would you code a SELECT construct instead of IF statements?When you have a long series of mutually exclusive conditions and the comparison is numeric, using a SELECT group is slightly more efficient than using IF-THEN or IF-THEN-ELSE statements because CPU time is reduced.

SELECT GROUP:
Select: begins with select group.When: identifies SAS statements that are executed when a particular condition is true.
Otherwise (optional): specifies a statement to be executed if no WHEN condition is met.
End: ends a SELECT group.

·What statement you code to tell SAS that it is to write to an external file?
.What statement do you code to write the record to the file?
PUT and FILE statements.

· If reading an external file to produce an external file, what is the shortcut to write that record without coding every single variable on the record?
· If you're not wanting any SAS output from a data step, how would you code the data statement to prevent SAS from producing a set?Data _Null_

· What is the one statement to set the criteria of data that can be coded in any step?Options statement: This a part of SAS program and effects all steps that follow it.

· Have you ever linked SAS code? If so, describe the link and any required statements used to either process the code or the step itselfNo
.· How would you include common or reuse code to be processed along with your statements?By using SAS Macros.

· When looking for data contained in a character string of 150 bytes, which function is the best to locate that data: scan, index, or indexc?
SCAN.· If you have a data set that contains 100 variables, but you need only five of those,

.what is the code to force SAS to use only those variable?Using KEEP option or statement.

· Code a PROC SORT on a data set containing State, District and County as the primary variables, along with several numeric variables.

Proc sort data=one;
BY State District County ;
Run ;
· How would you delete duplicate observations?NODUP Option in proc sort

· How would you delete observations with duplicate keys?NODUPKEY Option in proc sort

· How would you code a merge that will keep only the observations that have matches from both sets.Check the condition by using If statement in the Merge statement while merging datasets.

· How would you code a merge that will write the matches of both to one data set, the non-matches from the left-most data.
Step1: Define 3 datasets in DATA step
Step2: Assign values of IN statement to different variables for 2 datasets
Step3: Check for the condition using IF statement and output the matching to first dataset and no matches to different datasets

Ex:

data xxx;
merge yyy(in = inxxx) zzz (in = inzzz);
by aaa;
if inxxx = 1 and inyyy = 1;
run;

· What is the Program Data Vector (PDV)? What are its functions?Function: To store the current obs;PDV (Program Data Vector) is a logical area in memory where SAS creates a dataset one observation at a time. When SAS processes a data step it has two phases. Compilation phase and execution phase. During the compilation phase the input buffer is created to hold a record from external file. After input buffer is created the PDV is created. The PDV is the area of memory where SAS builds dataset, one observation at a time. The PDV contains two automatic variables _N_ and _ERROR_.


The Logical Program Data Vector (PDV) is a set of buffers that includes all variables referenced either explicitly or implicitly in the DATA step. It is created at compile time, then used at execution time as the location where the working values of variables are stored as they are processed by the DATA step program(source: http://www2.sas.com/proceedings/sugi24/Posters/p235-24.pdf).

· Does SAS 'Translate' (compile) or does it 'Interpret'? Explain.SAS compiles the code· At compile time when a SAS data set is read, what items are created?Automatic variables are created. Input Buffer, PDV and Descriptor Information

· Name statements that are recognized at compile time only?PUT

· Name statements that are execution only.INFILE, INPUT·

.Identify statements whose placement in the DATA step is critical.DATA, INPUT, RUN.

· Name statements that function at both compile and execution time.INPUT

· In the flow of DATA step processing, what is the first action in a typical DATA Step?The DATA step begins with a DATA statement. Each time the DATA statement executes, a new iteration of the DATA step begins, and the _N_ automatic variable is incremented by 1.

· What is _n_?It is a Data counter variable in SAS.
Note: Both -N- and _ERROR_ variables are always available to you in the data step

.–N- indicates the number of times SAS has looped through the data step.This is not necessarily equal to the observation number, since a simple sub setting IF statement can change the relationship between Observation number and the number of iterations of the data step.The –ERROR- variable ha a value of 1 if there is a error in the data for that observation and 0 if it is not. Ex: This is nothing but a implicit variable created by SAS during data processing. It gives the total number of records SAS has iterated in a dataset. It is Available only for data step and not for PROCS. Eg. If we want to find every third record in a Dataset thenwe can use the _n_ as follows

Data new-sas-data-set;
Set old;
if mod(_n_,3)= 1 then;
run;
Note: If we use a where clause to subset the _n_ will not yield the required result.


How do i convert a numeric variable to a character variable?You must create a differently-named variable using the PUT function.

How do i convert a character variable to a numeric variable?You must create a differently-named variable using the INPUT function.

How can I compute the age of something?Given two sas date variables born and calc:

age = int(intck('month',born,calc) / 12);
if month(born) = month(calc) then age = age - (day(born) > day(calc));

How can I compute the number of months between two dates? Given two sas date variables begin and end:

months = intck('month',begin,end) - (day(end) <>

How can I determine the position of the nth word within a character string?
Use a combination of the INDEXW and SCAN functions:pos = indexw(string,scan(string,n));

I need to reorder characters within a string...use SUBSTR?You can do this using only one function call with TRANSLATE versus two functions calls with SUBSTR. The following lines each move the first character of a 4-character string to the last:
reorder = translate('2341',string,'1234');
reorder = substr(string,2,3) substr(string,1,1);How can I put my sas date variable so that December 25, 1995 would appear as '19951225'? (with no separator)

use a combination of the YEAR. and MMDDYY. formats to simply display the value:
put sasdate year4. sasdate mmddyy4.;

or use a combination of the PUT and COMPRESS functions to store the value:
newvar = compress(put(sasdate,yymmdd10.),'/');

How can I put my sas time variable with a leading zero for hours 1-9?
Use a combination of the Z. and MMSS. formats:
hrprint = hour(sastime);
put hrprint z2. ':' sastime mmss5.;


INFILE OPTIONSPrepared by Sreeja E V(sreeja@kreara.com) source: kreara.blogspot.com.
Infile has a number of options available.


FLOWOVER

FLOWOVER is the default option on INFILE statement. Here, when the INPUT statement reaches the end of non-blank characters without having filled all variables, a new line is read into the Input Buffer and INPUT attempts to fill the rest of the variables starting from column one. The next time an INPUT statement is executed, a new line is brought into the Input Buffer.
Consider the following text file containing three variables id, type and amount.
11101 A
11102 A 100
11103 B 43
11104 C
11105 C 67


The following SAS code uses the flowover option which reads the next non missing values for missing variables.

data B;
infile "External file" flowover;
input id $ type $ amount;
run;

which creates the following dataset



MISSOVERWhen INPUT reads a short line, MISSOVER option on INFILE statement does not allow it to move to the next line. MISSOVER option sets all the variables without values to missing.
data B;
infile "External file" missover;
input id $ type $ amount;
run;

which creates the following dataset

TRUNCOVERCauses the INPUT statement to read variable-length records where some records are shorter than the INPUT statement expects. Variables which are not assigned values are set to missing.
Difference between TRUNCOVER and MISSOVER

Both will assign missing values to variables if the data line ends before the variable’s field starts. But when the data line ends in the middle of a variable field, TRUNCOVER will take as much as is there, whereas MISSOVER will assign the variable a missing value.
Consider the text file below containing a character variable chr.
a
bb
ccc
dddd
eeeee
ffffff
Consider the following SAS code
data trun;
infile "External file" truncover;
input chr $3. ;
run;

When using truncover option we get the following dataset

data miss;
infile "External file" missover;
input chr $3. ;
run;
While using missover option we get the output

%include statement: which looks like a macro but isn't really, sucks the contents of the just-generated file into the input stream. The result will be that the step will effectively contain all of the rename statements generated in the previous step, accomplishing the renaming of all columns
Read more...