Pages

Showing posts with label SAS. Show all posts
Showing posts with label SAS. Show all posts

Wednesday, July 31, 2013

Basics of R 1

1.What should you type in the R console to install the "car" package?
install.packages("car")

2.Once you have this package installed, what should you type in the R console to load the ”car” package?
library(car)

3.What should you type in the R console to check what packages you have installed and loaded on your computer?  search()

4.What should you type to get help about the “data.frame” function? 
?data.frame

5.Create two vectors, the first one named "numbers" including all natural numbers from 1 to 10, and the second one named "words" containing the following series:"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten". From these two vectors, create a dataframe "nw" with each vector as a separate column. What should you type to check the attributes of "nw"?
attributes(nw)

6.What command should you type to get R to return the number “8” from the dataframe "nw"?
nw[8,1]
7.What command should you type to get R to return the word “eight” from the dataframe "nw"?
nw[8,2]

8.What should you type to create a matrix “a” comprising all natural numbers from 1 to 10, with 2 rows and 5 columns.
a=matrix(1:10,2,5)

9.Create a vector "x" comprising all natural numbers from 1 to 6 and another vector "y" comprising all natural numbers from 5 to 10. What should you type to combine them in a matrix of 2 rows and 6 columns?
rbind(x,y)

10.Create a vector "x" comprising all natural numbers from 1 to 6 and another vector "y" comprising all natural numbers from 5 to 10. What should you type to combine them in a matrix of 6 rows and 2 columns?
cbind(x,y)



Wednesday, May 15, 2013

concepts on DLM, DSD

The contents of the SAS data set PERM.JAN_SALES are listed below:

VARIABLE NAME TYPE
idnum character variable
sales_date numeric date value
A comma delimited raw data file needs to be created from the PERM.JAN_SALES data set. The SALES_DATE values need to be in
a MMDDYY10 form.
Which one of the following SAS DATA steps correctly creates this raw data file?

A. libname perm 'SAS-data-library';
data _null_;
set perm.jan_sales;
file 'file-specification' dsd = ',';
put idnum sales_date : mmddyy10.;
run;

B. libname perm 'SAS-data-library';
data _null_;
set perm.jan_sales;
file 'file-specification' dlm = ',';
put idnum sales_date : mmddyy10.;
run;

C. libname perm 'SAS-data-library';
data _null_;
set perm.jan_sales;
file 'file-specification';
put idnum sales_date : mmddyy10. dlm = ',';
run;

D. libname perm 'SAS-data-library';
data _null_;
set perm.jan_sales;
file 'file-specification';
put idnum sales_date : mmddyy10. dsd = ',';
run;
The correct answer is: B
concepts :-
DSD = ',' is invalid because by default DSD is a comma. If you use DSD alone it would work.

First, in put statement, $ sign for character variable, Idnum is not needed.
Ans, A is not correct as the default delimeter (,) for DSD is defined as dsd = ','. It is correct if it was used as: DSD
Ans C and D are not correct because of using the options dlm and dsd in PUT statement. They are the INFILE options

Tuesday, May 7, 2013

SAS interview questions

Following are the most frequent n favourite question of SAS Interviewers :- 

1.What SAS statements would you code to read an external raw data file to a DATA step? 
2.How do you read in the variables that you need? 
3.Are you familiar with special input delimiters? How are they used? 
4.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? 
5.What is the difference between an informat and a format? Name three informats or formats. 
6.Name and describe three SAS functions that you have used, if any? 
7.How would you code the criteria to restrict the output to be produced? 
8.What is the purpose of the trailing @? The @@? How would you use them? 
9.Under what circumstances would you code a SELECT construct instead of IF statements? 
10.What statement do 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? 
11.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? 
12.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? 
13.What is the one statement to set the criteria of data that can be coded in any step? 
14.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. 
15.How would you include common or reuse code to be processed along with your statements? 
16.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? 
17.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? 
18.Code a PROC SORT on a data set containing State, District and County as the primary variables, along with several numeric variables. 
19.How would you delete duplicate observations? 
20.How would you delete observations with duplicate keys? 
21.How would you code a merge that will keep only the observations that have matches from both sets. 
22.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 set to a second data set, and the non-matches of the right-most data set to a third data set. 
23.What is the Program Data Vector (PDV)? What are its functions? 
24.Does SAS ‘Translate’ (compile) or does it ‘Interpret’? Explain. 
25.At compile time when a SAS data set is read, what items are created? 
26.Name statements that are recognized at compile time only? 
27.Identify statements whose placement in the DATA step is critical.

Sunday, December 9, 2012

How do I read/write Excel files in SAS?


Reading an Excel file into SAS

Suppose that you have an Excel spreadsheet called auto.xls. The data for this spreadsheet are shown below.
MAKE           MPG  WEIGHT PRICE
AMC Concord    22   2930  4099
AMC Pacer      17   3350  4749
AMC Spirit     22   2640  3799
Buick Century  20   3250  4816
Buick Electra  15   4080  7827
Using the Import Wizard is an easy way to import data into SAS.  The Import Wizard can be found on the drop down file menu.  Although the Import Wizard is easy it can be time consuming if used repeatedly.  The very last screen of the Import Wizard gives you the option to save the statements SAS uses to import the data so that they can be used again.  The following is an example that uses common options and also shows that the file was imported correctly.
PROC IMPORT OUT= WORK.auto1 DATAFILE= "C:\auto.xls" 
            DBMS=xls REPLACE;
     SHEET="auto1"; 
     GETNAMES=YES;
RUN;
  • The out= option in the proc import tells SAS what the name should be for the newly-created SAS data file and where to store the data set once it is imported. 
  • Next the datafile= option tells SAS where to find the file we want to import. 
  • The dbms= option is used to identify the type of file being imported. 
  • The replace option will overwrite an existing file.
  • To specify which sheet SAS should import use the sheet="sheetname" statement.  The default is for SAS to read the first sheet.  Note that sheet names can only be 31 characters long.
  • The getnames=yes is the default setting and SAS will automatically use the first row of data as variable names.  If the first row of your sheet does not contain variable names use the getnames=no. 

Writing Excel files out from SAS

It is very easy to write out an Excel file using proc export in SAS.
Here is a sample program that writes out SAS data called mydata to an Excel file called mydata.xls into the directory "c:\dissertation".
proc export data=mydata outfile='c:\mydata.xls' dbms = xls replace;
run;

Friday, June 22, 2012

How to export SAS results to an Excel spreadsheet?

In order to use the techniques , you must have the following software:
1. Base SAS 9.1.3 or later, on any supported operating system and hardware.
2. Microsoft Excel 2002 or later (also referred to as Microsoft Excel XP).
3. An updated version of the SAS ExcelXP ODS tagset.

We will be using the Output Delivery System (ODS) to do so.  ODS allows you to generate tabular output from your raw output that can be placed into Excel sheets.  In the code below, we are creating an Excel file (giving it a name and location), indicating a style to be used ("minimal" in this example), and specifying a few other options. 
ODS TAGSETS.EXCELXP
file='D:\work\sas9\regression.xls'
STYLE= minimal
OPTIONS ( Orientation = 'landscape'
FitToPage = 'yes'
Pages_FitWidth = '1'
Pages_FitHeight = '100' );
 
ODS TAGSETS.EXCELXP file='D:\work\sas9\tab2.xls' STYLE=Printer OPTIONS ( Orientation = 'landscape' FitToPage = 'yes' Pages_FitWidth = '1' Pages_FitHeight = '100' embedded_titles = 'yes'); 

The first ODS statement ( ) closes the LISTING destination, which writes output to a listing file in batch mode, or to
the Output window when SAS is run interactively. We only want to generate XML output for use with Excel.
The second ODS statement ( ) uses the ExcelXP tagset to generate the XML output and then stores the output in a
file. The STYLE option controls the appearance of the output, such as the font and color scheme. To see a list of
ODS styles that are available for use at your site, submit the following SAS code:
ods listing;
proc template; list styles; run; quit;
The third ODS statement ( ) closes and releases the XML file so that it can be opened with Excel.

We employed a few of the "options" to format our results in Excel.  To see the full list of options, run the SAS code below:
filename temp temp; ods tagsets.ExcelXP file=temp options(doc='help'); ods tagsets.ExcelXP close;

USING ODS TO CREATE THE MULTI-SHEET EXCEL WORKBOOK
By default, the ExcelXP tagset will create a new worksheet each time a SAS procedure creates new tabular output.
Our sample code executes the REPORT procedure to create the first worksheet. Subsequent worksheets are
created by the PRINT procedure, with a new worksheet being created for each distinct BY group.



SAS CODE TO CREATE THE EXCEL WORKBOOK
Here is a listing of the basic SAS code used to create the Excel workbook:

options center;
ods listing close;
ods tagsets.ExcelXP path='output-directory' file='trial.xml' style=XLsansPrinter;
* Create a summary table to use as the summary/table of contents;
proc means data=sample.trial sum noprint;
by patient;
var arrhythmia flutteratr angina;
id sex drug;
output out=trialsummary(drop=_type_ _freq_) sum=;
run; quit;
* Create the summary/table of contents worksheet;
title 'Summary of Adverse Events';
footnote;
proc report nowindows data=trialsummary split='*';
columns patient sex drug arrhythmia flutteratr angina;
define patient / display;
define sex--drug / display;
define arrhythmia--angina / analysis n;
rbreak after / summarize;
run; quit;
* Create the detailed worksheets for each patient;
title 'Patient Visit Log';
footnote 'Click to return to AE Summary';
options missing=' ';
proc print data=sample.trial noobs label split='*';
by patient sex drug dosage;
pageby patient;
id visit visitdate;
var systolic diastolic;
var arrhythmia flutteratr angina;
label patient = 'Patient'
sex = ' Gender'
drug = ' Treatment'
dosage = ' Dosage (mg)';
run; quit;
options missing='.';
ods tagsets.ExcelXP close;

Asone can see ( ), the ExcelXP tagset is used to generate the output, and the XLsansPrinter style is used to
control the appearance aspects of the output. The MEANS procedure ( ) is used to create a summary table, and
PROC REPORT ( ) is run to create the first worksheet based on this summarized data. The PRINT procedure ( )



Tuesday, June 12, 2012

Creating a new variable by compressing several variables

Creating a new variable by compressing several variables


test family rep female male tree
1 A 1 F43 M28 1
1 B 1 F22 M02 2
1 B 2 F22 M02 4

data a ; set a;
ID=compress(test||family||rep||tree); *Combine factors using ||, remove any trailing blank using COMPRESS;

CROSSno=trim(female||male); *Combine FEMALE and MALE variables with ||, remove any trialing blank using TRIM;
CROSSblank=female||male ; * Trim or Compress is not used. New variable may contain blanks;

Proc print data=a ; run;
Result:

test family rep female male tree ID CROSSno CROSSblank
1 A 1 F43 M28 1 1A11 F43M28 F43 M28 
1 B 1 F22 M02 2 1B12 F22M02 F22 M02
1 B 2 F22 M02 4 1B24 F22M02 F22 M02

Using DIF and LAG functions

Using DIF and LAG functions

DIF function creates a new variable (D) by taking the difference of observations of another variable (X).Syntax, DIF<n>(argument); *<-- n specifies number of LAGS

data two;
input X @@;
Z=lag(x);
D=dif(x);
datalines;
1 2 6 4 7;
proc print data=two;
run;

Results of the PROC PRINT step follow:
X Z D
1 . .
2 1 1
6 2 4
4 6 – 2

Grouping variables or creating a new variable using

Grouping variables or creating a new variable using
IF/THEN ELSE statement

data a;
input dens percent @@;
datalines;
0.453 0.42..0.470 0.46..0.396 0.39 .0.430 0.46
;
run;

data a; set a ;
if dens>=0.450 and percent>=0.40 then type='T';
else type='J' ;
run; 

If you need to kill a SAS job, after issuing the kill -9 job# command

If you need to kill a SAS job, after issuing the kill -9 job# command

Use the following command to delete the SAS work directory related to this job:

cleanwork /tmp

=> you don't need to go to the /tmp directory to locate and remove your SAS  working directory.

Hint:
For this to work, add the following to your setenv PATH statement in your .cshrc file:
/usr/local/src/sas612/utilities/bin

(if you put this at the end of setenv PATH statement, don't forget the ":" before this path).

Lost SAS Code

If you happen to be one of the unlucky programmers who lost the SAS code … because you didn’t save it. There is solution for that…. SAS System automatically takes the backup of the SAS code for every 10 minutes (default);

Just look in the following location:

C:\Documents and Settings\Programmer Name\Application Data\SAS\EnhancedEditor\


Note: Replace “Programmer Name” with your login user id of the System you are using;If you go the specified location above, you will see a copy of the unsaved version of the SAS code.It will be quick if you search files with the extension name ‘.SAS’ (extension for auto-saved SAS codes)

If you want, you can also change the 10-minute time interval for Auto save…. Go to…
Tools ► Options ► Preferences ►Edit.
In the preferences dialog box, make sure to the change the time under Autosave every … And click on OK ..

How to use Lock Statement in SAS: -
A dataset may become locked explicitly using the LOCK statement or automatically if it is being modified by another SAS program. When a dataset has a lock on it, it cannot be read or modified until the lock is removed. One very easy method for waiting for the lock to be released is to use the FILELOCKWAIT libname option. For example,
libname MYLIB "/mypath/sunil" filelockwait=10;
If a dataset in MYLIB is locked and another SAS program attempts to read it, SAS will wait up to 10 seconds before giving an error.