DATA Step, Macro, Functions and more

Change Data Structure - Transpose from long to wide

Reply
Occasional Contributor
Posts: 13

Change Data Structure - Transpose from long to wide

[ Edited ]

Dear SAS users,

 

I have a large dataset with over 500k rows and over 100 variables (columns). However, I am interested particularlly in two columns called ID (identification) and LOC (location) assigned as values as A, B, or C. The ID column include multiple entries of same ID or sometimes single entry.

My question is, how I can create three additional columns say LOC1, LOC2, and LOC 3 of data based on oriiginal LOC. For example, say if the first ID 'A1000' has 6 entries (rows) with three rows of A, one of  B, and two of C in original LOC, now I want only one row of ID 'A1000' but three additional columns (LOC1, LOC2, LOC3) with a value of 3 in LOC1, with a value of 1 in LOC2, and similarly a value of 2 in LOC3.

 

I would appreciate very much for any help.

Thank you in advance.

 

 

Super User
Posts: 9,681

Re: Data management

proc freq data=sashelp.class noprint;
tables sex*age/out=temp list;
run;
proc transpose data=temp out=want;
by sex;
var count;
id age;
run;
Occasional Contributor
Posts: 13

Re: Data management

Thanks. I will try.

Super User
Posts: 17,831

Re: Data management

Do you want to keep the other 100 columns or are you okay dropping them entirely?

 

If you can drop them, look into proc transpose.

 

proc sort data=have;
by id loc;
run;

proc transpose data=have out=want prefix=LOC; by id; var LOC; run;
Occasional Contributor
Posts: 13

Re: Data management

Thanks. I will give a try keeping just two columns.
Super User
Super User
Posts: 7,401

Re: Change Data Structure - Transpose from long to wide

Hi,

 

In addition to the great answers given, you could also do it in a datastep:

data want;
  set have;
  by id loc;
  array loc_{3} 8;
  retain loc_:;
  if first.loc then call missing(of loc_{*});
  select(loc);
    when("A") loc_{1}=sum(loc_{1},1);
    when("B") loc_{2}=sum(loc_{2},2);
    when("C") loc_{3}=sum(loc_{3},3);
    otherwise;
  end;
  if last.id then output;
run;
Trusted Advisor
Posts: 1,115

Re: Change Data Structure - Transpose from long to wide

Hi @sijansap,

 

Here's another data step approach:

data want;
do until(last.id);
  set have(keep=id loc);
  by id;
  array x loc1-loc3;
  i=whichc(loc, 'A', 'B', 'C');
  if i then x{i}=sum(x{i},1);
end;
drop i loc;
run;

 

Ask a Question
Discussion stats
  • 6 replies
  • 336 views
  • 2 likes
  • 5 in conversation