Calculate the SUM for different year in SAS - sum

I have one dummy variable, emu3, where I have 1.560 observations if emu3=0 and 1.905 observations if emu3=1.
The data is for the period 1992-2006. I want to calculate the sum of the variable avgflow in each year when emu3=0 and emu3=1.
I have tried with this one:
PROC MEANS DATA=EMUdummy2 NWAY ;
CLASS emu3 ;
VAR avgflow ;
OUTPUT OUT=fam1 SUM=sumt;
RUN;
PROC PRINT DATA=fam1;
VAR sumt;
RUN;
But I am not sure if this is correct and I do not know how I do it for different year.
Can anyone help me?

Assuming you have a variable year, add it to the class statement in PROC MEANS.
PROC MEANS DATA=EMUdummy2 NWAY ;
CLASS emu3 year;
VAR avgflow ;
OUTPUT OUT=fam1 SUM=sumt;
RUN;
Also, add emu3 and year to your PROC PRINT
PROC PRINT DATA=fam1;
VAR emu3 year sumt;
RUN;
If you have a date variable (I'll assume it is called DATE) but no year variable, then you can create a YEAR variable like this:
data emudummy2;
set emudummy2;
year = year(date);
run;

Related

How do I "conditionally" count missing values per variable in PROC SQL?

I'm measuring expenses in different categories. I have two types of variables. A categorical variables which states if the respondent have had expenses in the category (such as "Exkl_UtgUtl_Flyg") and I have numerical variables (such as UtgUtl_FlygSSEK_Pers), which provides information on the amount spent by each respondent in that category.
I want to create a table which tells me if there are missing values in my numerical variables for categories where expenses have been reported (so missing values of "UtgUtl_FlygSSEK_Pers" where the variable "Exkl_UtgUtl_Flyg" equals 1, in an example with only one variable).
This works in a simple SQL query, so something like:
PROC SQL;
SELECT nmiss(UtgUtl_FlygSSEK_Pers)
FROM IBIS3_5
WHERE Exkl_UtgUtl_Flyg=1;
quit;
But I don't want to navigate between 20 different datasets to find my missing values, I want them all in the same table. I figure this should be possible if i write a subquery in the SELECT clause for each variable, so something like:
PROC SQL;
SELECT (SELECT nmiss(UtgUtl_FlygSSEK_Pers)
FROM IBIS3_5
WHERE Exkl_UtgUtl_Flyg=1) as nmiss_variable_1
FROM IBIS3_5;
quit;
This last query does not seem to work, however. It does not return a single value, but one value for each row in the dataset.
How do I make this work?
I suspect you want to generate a single value.
Either the total number of mis-matches.
select sum(missing(UtgUtl_FlygSSEK_Pers) and Exkl_UtgUtl_Flyg=1) as nmiss
from ibis3_5
;
Or perhaps just a binary 1/0 flag of whether or not there are any mismatches.
select max(missing(UtgUtl_FlygSSEK_Pers) and Exkl_UtgUtl_Flyg=1) as any_miss
from ibis3_5
;
Maybe a good usage of proc freq instead. Especially if you have multiple values.
Not all of this is necessary but this is a missing report. Depends exactly how you're defining missing of course.
*create sample data to work with;
data class;
set sashelp.class;
if age=14 then
call missing(height, weight, sex);
if name='Alfred' then
call missing(sex, age, height);
label age="Fancy Age Label";
run;
*set input data set name;
%let INPUT_DSN = class;
%let OUTPUT_DSN = want;
*create format for missing;
proc format;
value $ missfmt ' '="Missing" other="Not Missing";
value nmissfmt .="Missing" other="Not Missing";
run;
*Proc freq to count missing/non missing;
ods select none;
*turns off the output so the results do not get too messy;
ods table onewayfreqs=temp;
proc freq data=&INPUT_DSN.;
table _all_ / missing;
format _numeric_ nmissfmt. _character_ $missfmt.;
run;
ods select all;
*Format output;
data long;
length variable $32. variable_value $50.;
set temp;
Variable=scan(table, 2);
Variable_Value=strip(trim(vvaluex(variable)));
presentation=catt(frequency, " (", trim(put(percent/100, percent7.1)), ")");
keep variable variable_value frequency percent cum: presentation;
label variable='Variable' variable_value='Variable Value';
run;
proc sort data=long;
by variable;
run;
*make it a wide data set for presentation, with values as N (Percent);
proc transpose data=long out=wide_presentation (drop=_name_);
by variable;
id variable_value;
var presentation;
run;
*transpose only N;
proc transpose data=long out=wide_N prefix=N_;
by variable;
id variable_value;
var frequency;
run;
*transpose only percents;
proc transpose data=long out=wide_PCT prefix=PCT_;
by variable;
id variable_value;
var percent;
run;
*final output file;
data &Output_DSN.;
merge wide_N wide_PCT wide_presentation;
by variable;
drop _name_;
label N_Missing='# Missing' N_Not_Missing='# Not Missing'
PCT_Missing='% Missing' N_Not_Missing='% Not Missing' Missing='Missing'
Not_missing='Not Missing';
run;
title "Missing Report of &INPUT_DSN.";
proc print data=&output_dsn. noobs label;
run;

Error when using a Macro variable in DO loop in SAS: Required operator not found in expression

I'm using SAS and I need to combine a number of tables, each of which has suffix of month and year in their name. The specific tables to use will be variable depending on user-defined start and end date. To achieve this, I'm trying to use a do loop via a macro to loop through the months/years in the date range and append to the previous table. However, I'm having issues (seemingly to do with it using the macro variable for the start/end year in the loop). I receive the following errors:
ERROR: Required operator not found in expression: &start_year.
ERROR: The %FROM value of the %DO QUOTE_YEAR loop is invalid.
ERROR: Required operator not found in expression: &end_year.
ERROR: The %TO value of the %DO QUOTE_YEAR loop is invalid.
ERROR: The macro GET_PRICES will stop executing.
Here is some example test code I've come up with that replicates the issue which produced the errors above which I am trying to debug. Note for this example, I'm only looping through the years. (I will add the months in once I resolve this issue.)
DATA _NULL_;
FORMAT start_date end_date DATE9.;
start_date = '01JUL2018'd;
end_date = '30JUN2019'd;
CALL SYMPUT('start_date',start_date);
CALL SYMPUT('end_date',end_date);
RUN;
%MACRO get_prices(start_date, end_date);
%LET start_year = year(&start_date.);
%LET end_year = year(&end_date.);
%LET start_month = month(&start_date.);
%LET end_month = month(&end_date.);
DATA test;
t = 0;
RUN;
%DO quote_year = &start_year. %TO &end_year.;
DATA test2;
t = &quote_year.;
RUN;
PROC APPEND BASE= test DATA= test2;
%END;
%MEND;
%get_prices(&start_date.,&end_date.);
The expected output is a table with a single column 't', with 3 rows: (0, 2018, 2019). (The 0 value I just included to initialise a non-empty table on which to append.) The code works when I replace the macro variables to the start/end year in the loop values to their actual value.
Doesn't Work
%DO quote_year = &start_year. %TO &end_year.;
Works
%DO quote_year = 2018 %TO 2019;
I can't work out what is causing this to fail. I believe it must have something to do with the way I've defined the macro variables, but the strange thing is if I remove the do loop completely and have the following data step under the %LET statements, the values appear as expected.
DATA test_macro_values;
s = &start_year.;
t = &end_year.;
u = &start_month.;
v = &end_month.;
RUN;
Can anyone see what's going wrong?
There are no macro functions called year and month. You should use %sysfunc:
%LET start_year = %sysfunc(year(&start_date.));
%LET end_year = %sysfunc(year(&end_date.));
%LET start_month = %sysfunc(month(&start_date.));
%LET end_month = %sysfunc(month(&end_date.));

Format the summarised variables from proc summary

I'm using a Proc Summary, as I want to utilise a multilabel format. I've been going round and round trying to apply a format to my summarised outputs, but can't see how to get this without incurring warnings.
Proc Summary Data = Source CompleteTypes Missing NoPrint NWay;
Class Brand / MLF;
Var Id Total;
Output Out = Results
N(ID) = Volume
Sum(Total) = Grand_Total;
Run;
I want to format my Volume as Comma23. and the Grand_Total as Comma23.2. If I put a format statement after the outputs it warns me that the variables don't exist, but the dataset does have the format applied.
I would have thought that formatting a summarised variable would be a common action, but I can't find a way to apply it without getting the warnings. Is there something I'm missing?
Many thanks
Another approach is to use proc template to apply the format. The format will be carried over into the newly created data set using the ods output. Use ods trace on to find (1) the name of the template to alter (2) the name of the object to output into a data set. In your case, you want to alter the Base.Summary template and output the Summary object. Both will be found in the log when you run ods trace in front of a proc step. This can be done with other procedures as well. For instance, a proc frequency of a single table has the template Base.Freq.OneWayList
/* Create Test Data */
data test (drop = num);
do num = 1 to 100;
x = ceil(rand('NORMAL', 100, 10));
output;
end;
run;
/* Check log with ODS Trace On to find template to alter and object to output */
ods trace on;
proc summary data = test sum n mean print;
var x;
run;
ods trace off;
/* Alter the Base.Summary template */
ods path reset;
ods path (PREPEND) WORK.TEMPLATE(UPDATE);
proc template;
edit Base.Summary;
edit N;
label = 'Count';
header = varlabel;
format = Comma10.;
end;
edit Mean;
label = 'Average';
header = varlabel;
format = Comma10.;
end;
edit Sum;
label = "Sum";
header = varlabel;
format = Comma10.;
end;
end;
run;
/* Output Results (formatted) from the Proc */
ods output summary = results;
proc summary data = test sum n mean print stackodsoutput;
var x;
run;
Some statistics like SUM inherit the format of the analysis variable. N statistics does not inherit the format but you can format the new variable if you can use the : trick shown in the example, and no warning is produced.
proc summary data=sashelp.class;
class sex;
output out=test n(age)=Nage sum(weight)=sum_weight;
format nage: comma12. weight comma12.3;
run;
proc contents varnum;
run;
proc print;
run;
Use proc datasets to apply the format to your output dataset after proc summary has created it:
proc datasets lib = work;
modify results;
format Volume comma23. Grand_total comma23.2;
run;
quit;

SAS sql select variable as change name to a date in MonYY7. format

I am not sure if it is possible at all, but in case someone knows the answer. I need to select variables and rename them to dates in MonYY7. format. My understanding is that SAS stores dates as numbers, and it is the formats which represent them in the former way. However, would it be possible to somehow rename the variable's name itself according to the format?
Here is the code I have written:
%macro try;
%let month_count_back = 12;
%let today = %sysfunc(today());
%let sysmonth = %sysfunc(month("&sysdate"d));
proc sql;
create table try as
select *,
%do i = -&sysmonth. %to -&month_count_back.-&sysmonth.+1 %by -1;
max(month(FP_NDT) = month(intnx('month',&today.,&i.))) as mn%eval(&month_count_back.+&sysmonth.+&i.)
%if &i. = -&month_count_back.-&sysmonth.+1 %then %goto leave_month;
,
%leave_month:
%end;
from work.test
group by var;
quit;
run;
%mend try;
%try;
run;
It returns dummy indicators for each month value of the 'var' variable for the previous year (the intention here is to know which values are null and which are not). However, I would like each dummy variable created be named according to the month and the year it refers to. For example, m12 should be DEC2015, m11 - NOV2015 etc... As a corollary if month_count_back is equal to, say, 36 then m36 should be DEC2015, but M12 should be DEC2013 and M1 should be JAN2013 etc...
Maybe there is way to rename it later in a data step? I have tried to loop through it, but could not control for the changing month_count_back value...
Would appreciate any suggestions, thanks!

SAS/SQL - Create SELECT Statement Using Custom Function

UPDATE
Given this new approach using INTNX I think I can just use a loop to simplify things even more. What if I made an array:
data;
array period [4] $ var1-var4 ('day' 'week' 'month' 'year');
run;
And then tried to make a loop for each element:
%MACRO sqlloop;
proc sql;
%DO k = 1 %TO dim(period); /* in case i decide to drop something from array later */
%LET bucket = &period(k)
CREATE TABLE output.t_&bucket AS (
SELECT INTX( "&bucket.", date_field, O, 'E') AS test FROM table);
%END
quit;
%MEND
%sqlloop
This doesn't quite work, but it captures the idea I want. It could just run the query for each of those values in INTX. Does that make sense?
I have a couple of prior questions that I'm merging into one. I got some really helpful advice on the others and hopefully this can tie it together.
I have the following function that creates a dynamic string to populate a SELECT statement in a SAS proc sql; code block:
proc fcmp outlib = output.funcs.test;
function sqlSelectByDateRange(interval $, date_field $) $;
day = date_field||" AS day, ";
week = "WEEK("||date_field||") AS week, ";
month = "MONTH("||date_field||") AS month, ";
year = "YEAR("||date_field||") AS year, ";
IF interval = "week" THEN
do;
day = '';
end;
IF interval = "month" THEN
do;
day = '';
week = '';
end;
IF interval = "year" THEN
do;
day = '';
week = '';
month = '';
end;
where_string = day||week||month||year;
return(where_string);
endsub;
quit;
I've verified that this creates the kind of string I want:
data _null_;
q = sqlSelectByDateRange('month', 'myDateColumn');
put q =;
run;
This yields:
q=MONTH(myDateColumn) AS month, YEAR(myDateColumn) AS year,
This is exactly what I want the SQL string to be. From prior questions, I believe I need to call this function in a MACRO. Then I want something like this:
%MACRO sqlSelectByDateRange(interval, date_field);
/* Code I can't figure out */
%MEND
PROC SQL;
CREATE TABLE output.t AS (
SELECT
%sqlSelectByDateRange('month', 'myDateColumn')
FROM
output.myTable
);
QUIT;
I am having trouble understanding how to make the code call this macro and interpret as part of the SQL SELECT string. I've tried some of the previous examples in other answers but I just can't make it work. I'm hoping this more specific question can help me fill in this missing step so I can learn how to do it in the future.
Two things:
First, you should be able to use %SYSFUNC to call your custom function.
%MACRO sqlSelectByDateRange(interval, date_field);
%SYSFUNC( sqlSelectByDateRange(&interval., &date_field.) )
%MEND;
Note that you should not use quotation marks when calling a function via SYSFUNC. Also, you cannot use SYSFUNC with FCMP functions until SAS 9.2. If you are using an earlier version, this will not work.
Second, you have a trailing comma in your select clause. You may need a dummy column as in the following:
PROC SQL;
CREATE TABLE output.t AS (
SELECT
%sqlSelectByDateRange('month', 'myDateColumn')
0 AS dummy
FROM
output.myTable
);
QUIT;
(Notice that there is no comma before dummy, as the comma is already embedded in your macro.)
UPDATE
I read your comment on another answer:
I also need to be able to do it for different date ranges and on a very ad-hoc basis, so it's something where I want to say "by month from june to december" or "weekly for two years" etc when someone makes a request.
I think I can recommend an easier way to accopmlish what you are doing. First, I'll create a very simple dataset with dates and values. The dates are spread throughout different days, weeks, months and years:
DATA Work.Accounts;
Format Opened yymmdd10.
Value dollar14.2
;
INPUT Opened yymmdd10.
Value dollar14.2
;
DATALINES;
2012-12-31 $90,000.00
2013-01-01 $100,000.00
2013-01-02 $200,000.00
2013-01-03 $150,000.00
2013-01-15 $250,000.00
2013-02-10 $120,000.00
2013-02-14 $230,000.00
2013-03-01 $900,000.00
RUN;
You can now use the INTNX function to create a third column to round the "Opened" column to some time period, such as a 'WEEK', 'MONTH', or 'YEAR' (see this complete list):
%LET Period = YEAR;
PROC SQL NOPRINT;
CREATE TABLE Work.PeriodSummary AS
SELECT INTNX( "&Period.", Opened, 0, 'E' ) AS Period_End FORMAT=yymmdd10.
, SUM( Value ) AS TotalValue FORMAT=dollar14.
FROM Work.Accounts
GROUP BY Period_End
;
QUIT;
Output for WEEK:
Period_End TotalValue
2013-01-05 $540,000
2013-01-19 $250,000
2013-02-16 $350,000
2013-03-02 $900,000
Output for MONTH:
Period_End TotalValue
2012-12-31 $90,000
2013-01-31 $700,000
2013-02-28 $350,000
2013-03-31 $900,000
Output for YEAR:
Period_End TotalValue
2012-12-31 $90,000
2013-12-31 $1,950,000
As Cyborg37 says, you probably should get rid of that trailing comma in your function. But note you do not really need to create a macro to do this, just use the %SYSFUNC function directly:
proc sql;
create table output.t as
select %sysfunc( sqlSelectByDateRange(month, myDateColumn) )
* /* to avoid the trailing comma */
from output.myTable;
quit;
Also, although this is a clever use of user-defined functions, it's not very clear why you want to do this. There are probably better solutions available that will not cause as much potential confusion in your code. User-defined functions, like user-written macros, can make life easier but they can also create an administrative nightmare.
I could make all sorts of guesses as to why you're getting errors, but fundamentally, don't do it this way. You can do exactly what you're trying to do in a data step that is much easier to troubleshoot and much easier to implement than a FCMP function which is really just trying to be a data step anyway.
Steps:
1. Create a dataset that has your possible date pulls. If you're using this a lot, you can put this in a permanent library that is defined in your SAS AUTOEXEC.
2. Create a macro that pulls the needed date strings from it.
3. If you want, use PROC FCMP to make this a function-style macro, using RUN_MACRO.
4. If you do that, use %SYSFUNC to call it.
Here is something that does this:
1:
data pull_list;
infile datalines dlm='|';
length query $50. type $8.;
input type $ typenum query $;
datalines;
day|1|&date_field. as day
week|2|week(&date_field.) as week
month|3|month(&date_field.) as month
year|4|year(&date_field.) as year
;;;;
run;
2:
%macro pull_list(type=,date_field=);
%let date_field = datevar;
%let type = week;
proc sql noprint;
select query into :sellist separated by ','
from pull_list
where typenum >= (select typenum from pull_list where type="&type.");
quit;
%mend pull_list;
3:
proc fcmp outlib = work.functions.funcs;
function pull_list(type $,date_field $) $;
rc = run_macro('pull_list', type,date_field);
if rc eq 0 then return("&sellist.");
else return(' ');
endsub;
run;
4:
data test;
input datevar 5.;
datalines;
18963
19632
18131
19105
;;;;
run;
option cmplib = (work.functions);
proc sql;
select %sysfunc(pull_list(week,datevar)) from test;
quit;
One of the big advantages of this is that you can add additional types without having to worry about the function's code - just add a row to pull_list and it works. If you want to set it up to do that, I recommend using something other than 1,2,3,4 for typenum - use 10,20,30,40 or something so you have gaps (say, if "twoweek" is added, it would be between 2 and 3, and 25 is easier than 2.5 for people to think about). Create that pull_list dataset, put it on a network drive where all of your users can use it (if anybody beyond you uses it, or a personal one if not), and go from there.