Given a table like such:
Obs A B C D E
1 1 2 1 1 2
2 2 2 1 2 2
3 2 3 3 2 2
4 1 2 3 1 1
how do i create a column , summing the number of times the value of 1 occurs in the row?
Like this.
Obs A B C D E Count
1 1 2 1 1 2 3
2 2 2 1 2 2 1
3 2 3 3 2 2 0
4 1 2 3 1 1 3
Hi,
If the table values are only 1 digit numbers (0-9), then a simple count function can give the answer. I would combine all variables into a character string and count number 1 there.
data want;
set have;
char= catx(',', a, b, c, d, e);
count= countc(char, '1');
proc print; run;
You can use SAS array and examine the values of each column to match with 1, and count them.
data have;
input A B C D E;
datalines;
1 2 1 1 2
2 2 1 2 2
2 3 3 2 2
1 2 3 1 1
;
run;
data want;
set have;
array x[*] A B C D E;
count = 0;
do i = 1 to dim(x);
if x[i] = 1 then count + 1;
end;
drop i;
run;
proc print data = want;
run;
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.
Ready to level-up your skills? Choose your own adventure.