Write and run SAS programs in your web browser

Counting the number of occurrence of a variable in an observation

Accepted Solution Solved
Reply
New Contributor
Posts: 2
Accepted Solution

Counting the number of occurrence of a variable in an observation

I'm on SAS University Edition - I have a data set with 792 rows and 29 columns; each column is a variable with value "0" or "1".  I would like to make a table with 792 rows and a single column, with the value of the single column being the number of "1"s in the corresponding observation.

 

For example:

 

varA     varB     varC     varD

1          1           0          1

0          0           0          1

1          1           1          0

1          1           1          1

0          0           0          0

1          0           1          0

 

output:

3

1

3

4

0

2

 

Sorry if this is a basic question - I've new to SAS, and have looked around the forums and the internet without finding anything that has worked for me.  Much thanks!!


Accepted Solutions
Solution
‎07-23-2017 07:46 PM
Super User
Posts: 5,497

Re: Counting the number of occurrence of a variable in an observation

I'm thinking that your real variable names don't all begin with "var".  If you want the sum of all numeric variables, you could use:

 

data want;

set have;

new_column = sum(of _numeric_);

run;

 

There's not much point in putting this new column into a separate data set.  Once you do that, if you were to ever sort your data you couldn't match the new column back to the row that it came from.

View solution in original post


All Replies
PROC Star
Posts: 7,467

Re: Counting the number of occurrence of a variable in an observation

data want (keep=sum);
  set have;
  array vars(*) varA--VarD;
  sum=sum(of vars(*));
run;

Art, CEO, AnalystFinder.com

 

PROC Star
Posts: 325

Re: Counting the number of occurrence of a variable in an observation

this should work

data want(drop=var:);
 set have;
 finalvar=sum(of var:);
 run;
Solution
‎07-23-2017 07:46 PM
Super User
Posts: 5,497

Re: Counting the number of occurrence of a variable in an observation

I'm thinking that your real variable names don't all begin with "var".  If you want the sum of all numeric variables, you could use:

 

data want;

set have;

new_column = sum(of _numeric_);

run;

 

There's not much point in putting this new column into a separate data set.  Once you do that, if you were to ever sort your data you couldn't match the new column back to the row that it came from.

New Contributor
Posts: 2

Re: Counting the number of occurrence of a variable in an observation

Thanks, all! Looks like there a couple of ways to do this - I appreciate the help.

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 251 views
  • 1 like
  • 4 in conversation