简体   繁体   中英

sas how to do frequencies for only certain values

I have some survey data with possible responses, an example would be:

         Q1
Person1  Yes
Person2  No
Person3  Missing
Person4  Multiple Marks
Person5  Yes

I need to calculate the frequencies by question, so that only the Yes/No (other questions have varied responses such as frequently, very frequently, etc) are counted in the totals - not the ones with Multiple Marks. Is there a way to exclude these using proc freq or another method?

Outcome:

Yes: 2
No: 1
Total: 3

Using proc freq, I'd do something like this:

proc freq data=have (where=(q1 in ("Yes", "No")));
tables q1 / out=want;
run;

Output:

Q1  Count   Percent
No  1   33.333333333
Yes 2   66.666666667

Proc sql:

proc sql;
select 
    sum(case when q1 eq "Yes" then 1 else 0 end) as Yes
    ,sum(case when q1 eq "No" then 1 else 0 end) as No
    ,count(q1) as Total
from have
where q1 in ("Yes", "No");
quit;

Output:

Yes No Total 
2 1 3 

The best way to do this is using formats.

Rather than storing your data as character strings, you should be storing it as numeric variables. This allows you to use numeric missing values to code those values you don't consider proper responses; using formats allows you to have your cake and eat it to (ie, allows you to still have those nice pretty response labels).

Here's an example. To understand this, you need to understand SAS special missings . Note the missing statement tells SAS to consider a single "M" in the input as .M (and similar for D and R). I then show two PROC FREQ results, one with the missings excluded, one with them included, to show the difference.

proc format;
  value YNQF
   1 = 'Yes'
   2 = 'No'
   . = 'Missing'
   .M= 'Multiple Marks'
   .D= "Don't Know"
   .R= "Refused"
  ;
quit;

missing M R D;
data have;
  input Q1 Q2 Q3;
  format q1 q2 q3 YNQF.;
  datalines;
1 1 2
2 1 R
. . 1
M 1 1
1 . D
;;;;
run;

proc freq data=have;
  tables (q1 q2 q3);
  tables (q1 q2 q3)/missing;
run;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM