Home > Enterprise >  Calling the column values when the column names are date macro variables
Calling the column values when the column names are date macro variables

Time:03-02

In SAS, I have a dataset which has 5 columns and 4 rows. The column names are date macro variables.

I want to subtract the values in one column from another. (Date of column 4 - date of column 3) doesn't work. This subtracts the date itself and not the values in those columns.

How do I call the values of the columns?

Please help.

Example-- There are five columns-12/1/2019,12/1/2020,12/1/2021,12/1/2022 12/1/2023 and four rows-A,B,C,D and some values are stored in them.

In the above table, I want to add a column which prints the difference between the values on all dates for all the rows (A,B,C,D).

Also sim_date= 12/1/20, f_starting=12/1/2019, f_1=12/1/2021, f_2=12/1/2022, f_3=12/1/2023. These dates are all macro variables.

But when I write the code as

             data test;
             set test;
             format g0 g1 g2 g3 percent5.2 ;
             g0 = (&sim_date - &f_starting)/&f_starting;
             g1 = (&f_1 - &sim_date)/&sim_date  ;
             g2 = (&f_2 - &f_1)/&f_1  ;
             g3 = (&f_3- &f_2)/&f_2 ; 
             run; 
`````
This code subtracts the two dates instead of the values stored in the dates. How do I call the values?

CodePudding user response:

Use the "varname"n syntax so that SAS knows you are referring to the variable instead of the value.

data test;
set test;
format g0 g1 g2 g3 percent5.2 ;
g0 = ("&sim_date"n - "&f_starting"n)/"&f_starting"n;
g1 = ("&f_1"n - "&sim_date"n)/"&sim_date"n  ;
g2 = ("&f_2"n - "&f_1"n)/"&f_1"n  ;
g3 = ("&f_3"n - "&f_2"n)/"&f_2"n ; 
run; 

CodePudding user response:

You reference a variable by its name. So if your variables are named sim_date and f_starting then your code might be:

g0 = (sim_date - f_starting)/f_starting;

If your variables are actually using those non-standard names that start with digits or have slashes or other non standard characters in them then you need to use a name literal. That is a quoted string suffixed with the letter n. So if the variables are named 2022/01/01 and 2022/02/01 for the first days of the first two months of 2022 then your code needs to look like:

g0 = ("2022/02/01"n - "2022/01/01"n)/"2022/01/01"n;

So either set the macro variables to name literals.

%let sim_date="2022/02/01"n;
%let f_starting="2022/02/01"n;

and then your current code will work.

g0 = (&sim_date - &f_starting)/&f_starting;

Or leave your macro variables with strings that match the actual variable names and convert them to name literals when you use them in your code:

%let sim_date = 2022/02/01;
%let f_starting = 2022/01/01;
g0 = ("&sim_date"n - "&f_starting"n)/"&f_starting"n;
  • Related