Reading and Writing Data |
Although this book does not require previous knowledge of the SAS/IML language, experienced SAS/IML programmers might wonder how to transfer data between matrices and a DataObject. For completeness, this issue is addressed in this section.
The SAS/IML language provides statements to read and write server data to and from matrices. The USE statement opens a SAS data set, and the READ statement reads server data into matrices. The SAS/IML language also has a CREATE statement that creates a server data set and an APPEND statement that writes variables from matrices. These statements are documented fully in the SAS/IML User's Guide.
If you have data in SAS/IML matrices, you can create a DataObject from those matrices by using the Create method of the DataObject. For example, type the following statements into a SAS/IML Studio program window, and select Program Run from the main menu.
xy = {0 4, 1 6, 2 7, 3 9, 4 10}; declare DataObject dobjMatrix; dobjMatrix = DataObject.Create("Matrix", {"XVar" "YVar"}, xy);
The matrix xy is used to initialize the dobjMatrix DataObject. The result is a DataObject with two variables (named XVar and YVar) and five observations.
If the DataObject is already created, you can add a new variable to the DataObject by using the AddVar method. For example, add the following statements to the SAS/IML Studio program from the previous section, and select Program Run from the main menu.
z = {-1, 1, 0, 0, 1}; dobjMatrix.AddVar( "z", z); DataTable.Create( dobjMatrix );
The result is a DataObject with three variables (the new variable is z) and five observations. It is an error to try to add a new variable that has a different number of observations than the DataObject.
There is also a DataObject method, called the AddVars method, that enables you to add several variables in a single call.
You can copy data from the DataObject into a matrix by using the GetVarData method of the DataObject. For example, add the following statements to the SAS/IML Studio program from the previous section, and select Program Run from the main menu.
dobjMatrix.GetVarData( "XVar", x); print x;
The result is a matrix x that contains the values of the XVar variable. You can name the matrix anything you want. It can have the same name as the variable in the DataObject (as the z variable and matrix did) or a completely different name (as in this example). After the data are copied into a matrix, there is no linkage between the DataObject and the matrix: changing elements of the matrix does not affect the DataObject, and changing the DataObject does not affect the matrix.
The CopyServerDataToDataObject module uses this approach to read variables in a server data set directly into a DataObject. This module is discussed in Chapter 5, Adding Variables to the DataObject. Again, the number of observations in the server data set must match the number of observations in the DataObject.
Copyright © SAS Institute, Inc. All Rights Reserved.