SAS

2014-10-16 6 views
0

에 새로운 변수 만들기 나는 이런 식으로 뭔가 보이는 SAS의 패널 데이터 세트,이 각 개인에 대한SAS

DATA have; 

INPUT id time income; 

CARDS; 
1 2008 1000 
1 2009 900 
1 2010 1100 
2 2008 600 
2 2009 500 
2 2010 400 
3 2008 300 
3 2009 350 
3 2010 250 
; 
RUN; 

을, 그 개인의 소득에 새 열 (이름 income_id)를 만들려면 모든 기간 및 모든 다른 개인을위한 0. 그래서 기본적으로 내가 원하는 이것이다 :

DATA want; 
    INPUT id time income income_1 income_2 income_3; 
CARDS; 
1 2008 1000 1000 0 0 
1 2009 900 900 0 0 
1 2010 1100 1100 0 0 
2 2008 600 0 600 0 
2 2009 500 0 500 0 
2 2010 400 0 400 0 
3 2008 300 0 0 300 
3 2009 350 0 0 350 
3 2010 250 0 0 250 
; 
RUN; 

감사

답변

1

이 작업을 수행하는 직관적 인 방법은 매크로를 사용하는 것입니다.

이 작업을 수행하는 방법을 정확하게 설명하는 Yunchao Tian의 매우 훌륭한 SUGI가 있습니다. here.

나는 당신을 위해이 코드를 채택했다. 나는 그것을 테스트하고 괜찮아 보이는 것 같습니다.

proc sort data=have out=unique nodupkey; 
    by id; 
run; 

/* assign the largest value of id to the macro variable NMAX */ 
data _null_; 
    set unique end=last; 
    if last then call symput('NMAX', PUT(id, 3.)); 
run; 

/* create all macro variables and assign value 0*/ 
data _null_; 
    do i=1 to &NMAX; 
     call symput('M'||LEFT(PUT(i,3.)), '0'); 
    end; 
run; 

/* assign the value of id to the corresponding macro variable */ 
data _null_; 
    set have; 
    call symput('M'||LEFT(PUT(id,3.)), PUT(id,3.)); 
run; 

/* macro to create code to set col to income or zero */ 
%MACRO GETID; 
%DO I = 1 %TO &NMAX; 
    %IF &&M&I = 0 %THEN %GOTO OUT; 
     IF ID = &&M&I THEN income_&I = income; 
     ELSE income_&I = 0; 
    %OUT: %END; 
%MEND GETID; 

/* Execute the macro */ 
DATA want; 
SET have; 
    %GETID 
RUN; 

PROC PRINT DATA=want; 
RUN; 
0
/* find min and max id for array boundaries, if ID is numeric */ 

proc sql noprint; 
select put(min(id), 16. -L), put(max(id), 16. -L) into :minId, :maxId 
from have 
; 
quit; 

/* with zero-ing the other variables, could be slow if lots of distinct IDs */ 
data want1; 
set have; 
array arr_income income_&minId - income_&maxId; 
    do i=&minId to &maxId; 
     if i = id then arr_income[id] = income; 
     else arr_income[i] = 0; 
    end; 
run; 

/* without zero-ing the other variables */ 
data want2; 
set have; 
array arr_income income_&minId - income_&maxId; 
arr_income[id] = income; 
run; 

주 : 그는 문 array arr_income income_&minId - income_&maxId; 변수를 최소 및 최대, 또한 비 존재 사이의 모든 숫자 income_<i>을 만듭니다.

0
DATA have; 

INPUT id time income; 

CARDS; 
1 2008 1000 
1 2009 900 
1 2010 1100 
2 2008 600 
2 2009 500 
2 2010 400 
3 2008 300 
3 2009 350 
3 2010 250 
; 
RUN; 

proc sql; 
select count(distinct(id)) into :count from have; 
select distinct(id) into :id1 - :id%left(&count) from have; 
quit; 

%put &id1 &id2 &id3; 

options mprint; 

%macro test; 
data have2; 
set have ; 
by id time; 
%do i=1 %to &count; 
if id= &&id&i then income_&i=income;else income_&i=0; 
%end; 
run; 
%mend; 

%test; 

proc print data=have2; 
run;