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;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

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