BookmarkSubscribeRSS Feed
mcook
Quartz | Level 8

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  

 

2 REPLIES 2
A_Kh
Lapis Lazuli | Level 10

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; 
KachiM
Rhodochrosite | Level 12

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;

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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
  • 442 views
  • 0 likes
  • 3 in conversation