BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
PatrykSAS
Obsidian | Level 7

Hello

I'd like to transpose my table with counting occurrences. 

Source table:

ID VAR1 VAR2
1 HOME APPLE
1 AWAY BANANA
2 HOME BANANA
2 HOME APPLE

I wish I get result:

ID HOME AWAY APPLE BANANA
1 1 1 1 1
2 2 0 1 1

How can I do it?

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

Without having any values in code:

data have;
input ID $ VAR1 $ VAR2 $;
datalines;
1 HOME  APPLE
1 AWAY  BANANA
2 HOME  BANANA
2 HOME  APPLE
;

data first;
set have;
array vars {*} var:;
do i = 1 to dim(vars);
  var = vars{i};
  output;
end;
run;

proc freq data=first noprint;
tables id*var / out=want_long;
run;

proc transpose data=want_long out=want (drop=_name_ _label_);
by id;
var count;
id var;
run;

View solution in original post

2 REPLIES 2
tarheel13
Rhodochrosite | Level 12

It's not really transposing. You want to get counts within by groups. You could use proc means, proc SQL, proc summary. 

data test;
input ID var1 $ var2 $;
cards;
1 HOME APPLE
1 AWAY BANANA
2 HOME BANANA
2 HOME APPLE
;
proc print;
run;

proc sql;
	create table sums as 
	select ID, sum(var1='HOME') as home, sum(var1='AWAY') as away,
	sum(var2='APPLE') as apple, sum(var2='BANANA') as banana
		from test
		group by ID;
quit;
Kurt_Bremser
Super User

Without having any values in code:

data have;
input ID $ VAR1 $ VAR2 $;
datalines;
1 HOME  APPLE
1 AWAY  BANANA
2 HOME  BANANA
2 HOME  APPLE
;

data first;
set have;
array vars {*} var:;
do i = 1 to dim(vars);
  var = vars{i};
  output;
end;
run;

proc freq data=first noprint;
tables id*var / out=want_long;
run;

proc transpose data=want_long out=want (drop=_name_ _label_);
by id;
var count;
id var;
run;

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 446 views
  • 4 likes
  • 3 in conversation