Sample 24745: Collapse observations within a BY group into a single observation
The sample code on the Full Code tab illustrates how to rearrange a data set by changing a single variable in a group of observations to a group of variables in one observation. Reshape the data by collapsing observations within a BY group into a single observation in order to simplify data analysis and report generation.
These sample files and code examples are provided by SAS Institute
Inc. "as is" without warranty of any kind, either express or implied, including
but not limited to the implied warranties of merchantability and fitness for a
particular purpose. Recipients acknowledge and agree that SAS Institute shall
not be liable for any damages whatsoever arising out of their use of this material.
In addition, SAS Institute will provide no support for the materials contained herein.
/* Create sample data */
data students;
input name:$ score;
datalines;
Deborah 89
Deborah 90
Deborah 95
Martin 90
Stefan 89
Stefan 76
;
run;
data scores(keep=name score1-score3);
/* RETAIN prevents these variables from being set to missing at the top of */
/* the DATA step with each iteration */
retain name score1-score3;
/* An ARRAY statement is used to name the new variables */
array scores(*) score1-score3;
set students;
by name;
if first.name then do;
i=1;
/* Clear the array so that values from the last BY group are not carried forward */
call missing (of scores(*));
end;
/* Assign the values to the array elements */
scores(i)=score;
if last.name then output;
i+1;
run;
proc print;
run;
/* Alternate method using PROC TRANSPOSE to yield the same result */
proc transpose data=students out=new(drop=_name_) prefix=score;
by name;
var score;
run;
These sample files and code examples are provided by SAS Institute
Inc. "as is" without warranty of any kind, either express or implied, including
but not limited to the implied warranties of merchantability and fitness for a
particular purpose. Recipients acknowledge and agree that SAS Institute shall
not be liable for any damages whatsoever arising out of their use of this material.
In addition, SAS Institute will provide no support for the materials contained herein.
Obs name score1 score2 score3
1 Deborah 89 90 95
2 Martin 90 . .
3 Stefan 89 76 .
This sample shows you how to rearrange a data set by changing a single variable in a group of observations to a group of variables in one observation.
Type: | Sample |
Topic: | SAS Reference ==> DATA Step Data Management ==> Manipulation and Transformation ==> Array processing Data Management ==> Manipulation and Transformation ==> BY-group processing
|
Date Modified: | 2006-04-15 03:02:59 |
Date Created: | 2004-09-30 14:09:10 |
Operating System and Release Information
SAS System | Base SAS | All | n/a | n/a |