Hi Friend,
I have good SQL knowledge but new SAS learner, I need to count total number of observation from one data set
I am following below steps
data students;
input gender score;
cards;
1 48
1 45
2 50
2 42
1 41
2 51
1 52
1 43
2 52
;
run;
now I need total count from above table.
proc sql;
select count(*) from students1;
quit;
above queyr will give output 9 but when I am converting ths into SAS code
data students1;
set students;
count + 1;
by gender;
if first.gender then count = 1;
run;
proc print data = students1;
run;
above code I find out from the google and also this is not giving output 9. I am on a SAS learning stage . Please help
Can you please help me to correct the code and get the count 9
First of all, this happens:
31 data students1; 32 set students; 33 count + 1; 34 by gender; 35 if first.gender then count = 1; 36 run; ERROR: BY variables are not properly sorted on data set WORK.STUDENTS.
So you have to do
proc sort data=students;
by gender;
run;
before you try that data step.
Now you get that output:
Obs gender score count
1 1 48 1
2 1 45 2
3 1 41 3
4 1 52 4
5 1 43 5
6 2 50 1
7 2 42 2
8 2 51 3
9 2 52 4
You can see that the final counts for both values of gender add up to 9.
To get a simple total count, do this:
data students1;
set students;
count + 1;
run;
Now, you can get the total number of observations in a dataset much easier (and quicker, once the datasets grow) by querying its metadata:
proc sql;
select nobs from dictionary.tables where libname = 'WORK' and memname = 'STUDENTS';
quit;
Although you can count the number of obs using a data step you probably shouldn't. There are many ther ways to do so, one being querying the metadata tables and another is using a summary proc such as proc means or proc freq.
proc means data=students;
class gender;
run;
proc freq data=students;
tables gender;
run;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.