What is sas macro

What is sas macro

SAS – Макросы

SAS имеет мощную функцию программирования под названием Macros, которая позволяет нам избегать повторяющихся участков кода и использовать их снова и снова, когда это необходимо. Это также помогает создавать в коде динамические переменные, которые могут принимать разные значения для разных экземпляров прогона одного и того же кода. Макросы также могут быть объявлены для блоков кода, которые будут многократно использоваться аналогично макропеременным. Мы увидим оба из них в следующих примерах.

Макропеременные

Это переменные, которые содержат значение, которое будет снова и снова использоваться программой SAS. Они объявляются в начале программы SAS и вызываются позже в основной части программы. Они могут быть глобальными или локальными по объему.

Глобальная макро-переменная

Их называют глобальными макропеременными, потому что к ним может обращаться любая программа SAS, доступная в среде SAS. Как правило, это системные переменные, к которым обращаются несколько программ. Общий пример – системная дата.

пример

Ниже приведен пример переменной SAS с именем SYSDATE, которая представляет системную дату. Рассмотрим сценарий для печати системной даты в заголовке отчета SAS каждый день, когда отчет генерируется. Заголовок покажет текущую дату и день без кодирования каких-либо значений для них. Мы используем встроенный набор данных SAS под названием CARS, доступный в библиотеке SASHELP.

Когда приведенный выше код выполняется, мы получаем следующий вывод.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Локальная переменная макроса

Эти переменные могут быть доступны для программ SAS, в которых они объявлены как часть программы. Они, как правило, используются для предоставления разных varaibels одним и тем же операторам SAS, чтобы они могли обрабатывать разные наблюдения набора данных.

Синтаксис

Локальные переменные имеют декальтарный синтаксис.

Здесь поле «Значение» может принимать любое числовое, текстовое значение или значение даты, как того требует программа. Имя макрокоманды – это любая допустимая переменная SAS.

пример

Когда приведенный выше код выполняется, мы получаем тот же вывод, что и предыдущая программа. Но давайте изменим имя типа на «Wagon» и запустим ту же программу. Мы получим следующий результат.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Макро Программы

Макрос – это группа операторов SAS, на которые ссылается имя и которые можно использовать в программе где угодно, используя это имя. Он начинается с оператора% MACRO и заканчивается оператором% MEND.

Синтаксис

Локальные переменные объявлены с синтаксисом ниже.

пример

Приведенная ниже программа декальзирует группу STAT-сетей SAT под макросом с именем ‘show_result’; Этот макрос вызывается другими операторами SAS.

Когда приведенный выше код выполняется, мы получаем следующий вывод.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Обычно используемые макросы

SAS имеет много операторов MACRO, которые встроены в язык программирования SAS. Они используются другими программами SAS без явного объявления их. Общими примерами являются: завершение программы при выполнении какого-либо условия или запись значения переменной времени выполнения в журнал программы. Ниже приведены некоторые примеры.

Макро% PUT

Этот оператор макроса записывает текстовую или макропеременную информацию в журнал SAS. В приведенном ниже примере значение переменной «сегодня» записывается в журнал программы.

Когда приведенный выше код выполняется, мы получаем следующий вывод.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Макро% ВОЗВРАТ

Выполнение этого макроса вызывает нормальное завершение текущего выполняющегося макроса, когда определенное условие оценивается как истинное. В приведенном ниже примере, когда значение переменной «val» становится равным 10, макрос завершается, в противном случае он продолжается.

Когда приведенный выше код выполняется, мы получаем следующий вывод.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Макро% КОНЕЦ

Это макроопределение содержит цикл % DO% WHILE, который заканчивается, как требуется, оператором% END. В приведенном ниже примере макрос с именем test принимает пользовательский ввод и запускает цикл DO, используя это входное значение. Завершение цикла DO достигается с помощью оператора% end, в то время как конец макроса достигается с помощью оператора% mend.

Когда приведенный выше код выполняется, мы получаем следующий вывод.

SAS Macro Guide

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Table of Contents

SAS Institute, a leader in data analytics, has produced a software suite called Statistical Analysis System (SAS). SAS can help you with data management activities, business intelligence, advanced analytics, predictive analytics, and multivariate analysis.

Several conglomerates, such as Google, Facebook, Twitter, and Accenture, use SAS to answer the issues that arise at an organizational level, as well as to provide insightful reports. Project management, quality improvement, business forecasting, and operations research are all aided by it. It’s especially helpful for graphic design and app development.В

In this article, you will learn all about SAS Macros that help in writing the DRY (Don’t repeat yourself) code.

The Ultimate Data Science Job Guarantee Program

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

SAS Macro

SAS includes Macros, a unique programming feature that helps us to avoid writing repetitive code and reuse it when necessary. It also aids in the creation of dynamic variables that can take on changing values in the code depending on how the code is run. In the same way that macro variables can be initialized for blocks of code that will be reused several times, macros can be declared for blocks of code that will be reused multiple times.В

Let us now explore the variables within the SAS Macro.

What Are SAS Macro Variables?

The SAS variables store a value in a SAS program that can be utilized over and over again. These are declared at the beginning of a SAS program and then referenced later in the code. They can have a Local or Global focus.

Before getting into the implementation through examples, we must understand the different types of macro variables.В

So, let us look at the types of macro variables with examples.

What Are Local SAS Macro Variables?

SAS applications can access these variables if they are defined as a part of the program. These are usually used to provide alternative variables in the same SAS statements so that they can process diverse data set observations.

Syntax

% LET (Macro Variable Name) = Value;

In this, the Value field can include any numeric, text, or date value that the program requires. Any valid SAS variable can be used as the Macro variable name.

Example

The SAS statements utilize the variables by appending the ‘&’ character to the start of the variable name. The program below gathers all of the observations for the brand ‘Audi’ and the category ‘Sports.’ If we want a different make result, we must modify the variable make name value without changing anything else in the program. This variable reference can be many times in any SAS statement in the case of bring programs.

%LET make_name = ‘Audi’;

%LET type_name = ‘Sports’;

proc print data = sashelp.cars;

В В В TITLE «Sales as of &SYSDAY &SYSDATE»;

An Introduction to SAS Macro Programming

Published on: November 29, 2019

Macro programming is considered to be an advanced topic in SAS. Though macros can be challenging, it is also true that the basic concepts are not difficult to learn.

Assuming you know the basics of SAS Programming, In this tutorial, you will learn how the macro processor works and how to use SAS macros. The following article explains how you can create SAS macro variables.

Using these techniques, you can create efficient and reusable code that can save you time and effort.

Why use SAS macros?

Macros can automatically generate SAS codes and allow you to make more dynamic and generalized SAS programs. Macros can help significantly reduce the effort required to read or write repetitive SAS codes.

SAS program compilations

SAS codes are compiled and executed alternatively in steps. First, A data step

In a standard SAS program, SAS compiles and then immediately executes it. Whereas in macro code, there is an extra step.

SAS passes your macro statements to the macro processor, which then “resolves” your macros generating standard SAS code. Then, SAS can compile and execute the program.

The two essential elements of macro code are SAS macro variables

In the above example, &macro_var refers to a macro variable and %macro_var refers to a macro.

SAS Macro Parameters

For example, for calculating means, we often vary the set of variables

Positional vs. Keyword Parameters

You can specify macro parameters in two ways.

Positional Parameters

Keyword Parameters

Each of the above ways has its advantages. For example, you can apply a default value in a keyword parameter.

The default variable ‘age’ has been given in the above example of the keyword parameter.

The default variable will be considered ‘age’ if the macro is called without specifying any parameter.

Passing Multiple Parameters

A combination of positional and keyword parameters is primarily used; however, positional parameters must come before keyword parameters.

Working with Macro Strings

Macros and macro variables

Quotes are not necessary around the values of a macro variable. However, a period(.) is a signal in SAS to end a macro variable name if the requirement is to import data from a File

The below code doesn’t work.

Double vs Single Quotes in SAS Macros

Double quotes and single quotes affect SAS macro variables

This does not work.

This will work as a macro variable &filename is inside a double quote.

[Recomended Reading: SAS macro parameters with commas]

Evaluating Numeric Strings

Since SAS macro variables

The function %eval is used to obtain the integer or numeric value of an expression containing SAS macro variables

Floating-point evaluations can be performed with %sysevalf.

Conditional Statements

In SAS Macros, we can apply conditional statements using %IF %THEN, %DO,%WHILE, and %DO % UNTIl like below –

Output:

Control statements in macro are not valid in open code. They must be contained within macros.

SYMPUT and SYMGET

Macros are resolved before the execution of the data step

Output:

In the above example, the value in age macro is set to Age**2 as the macro statement was resolved before the data step

Output:

Using Symget:

SYMGET returns a character value of the maximum length of a data step

SYMGET returns a missing value if it cannot locate the macro variable identified as the argument

Debugging SAS macros

Debugging a macro code isn’t an easy process. It is difficult to identify the problem by seeing the ERROR messages. Hence, using the below system option, you can debug macros easily.

MLOGIC marks the beginning of macro execution. It shows the values resolved at macro invocation. Additionally, it shows a %IF condition is TRUE or FALSE.

The SYMBOLGEN system option writes the results of resolving macro to the SAS log for easy debugging.

In the above example, all three systems options have been enabled, showing detailed information about the macro in the SAS log.

You can refer to the SAS V8 documentation website for detailed information on troubleshooting steps in macros.

Related

Subhro

Subhro Kar is an Analyst with over five years of experience. As a programmer specializing in SAS (Statistical Analysis System), Subhro also offers tutorials and guides on how to approach the coding language. His website, 9to5sas, offers students and new programmers useful easy-to-grasp resources to help them understand the fundamentals of SAS. Through this website, he shares his passion for programming while giving back to up-and-coming programmers in the field. Subhro’s mission is to offer quality tips, tricks, and lessons that give SAS beginners the skills they need to succeed.

3 Easy Ways to Create a Macro Variable in SAS

A SAS macro variable is an extremely powerful tool to make your code more efficient. It helps you to make your code more dynamic and saves you a lot of time. However, how do you create a SAS macro variable?

In SAS, you create a macro variable with the %LET macro statement, the CALL SYMPUT routine, or the PROC SQL INTO clause. The %LET macro statement is appropriate for creating a single macro variable. The CALL SYMPUT routine and the PROC SQL INTO clause are more suited to create macro variables from SAS datasets.

In this article, we compare the three methods and discuss their pros and cons. We also show how to use these methods in real life by providing many examples.

Create a Macro Variable with the %LET Statement

The easiest way to create a macro variable in SAS is by using the %LET Macro Statement. This statement creates a macro variable and assigns it a value. You can also use the %LET statement to overwrite the existing value of a macro variable.

This is the syntax of the %LET statement:

The name of the macro variable must comply with the SAS naming convention. In other words, the name should start with an underscore or a letter from the Latin alphabet (A-Z, a-z). Also, the name must be 32 or fewer characters long and cannot contain blanks or special characters (except blanks).

The value of the macro variable is a character string or a number. If you omit the value, SAS creates a null value (i.e., a macro variable of length 0).

In the example below, we create a macro variable (my_name) and assign it a value (David).

Once you have created a macro variable, you can use the %PUT Macro Statement to display the value of the macro variable in the SAS log. You do so with the %PUT macro statement, followed by an ampersand (&), the name of the macro variable, and a semicolon. Additionally, you can add a dot after the name of your macro variable to make your code more readable.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Above we printed only the value of the macro variable to the log. Additionally, you can add normal text to the %PUT macro statement to make your code easier to understand.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

A special way of displaying a macro variable is by using the “&=” syntax. For example, &=my_name. By doing so, SAS prints the name of the macro variable and its value to the log.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Create a Macro Variable with Blanks

By default, the %LET macro statement removes leading and trailing blanks when you assign a value to a macro variable. However, in some cases, you might want to keep these blanks.

You create a SAS macro variable with leading and/or trailing blanks with the %STR() function. This function makes the blanks significant while assigning the value to the macro variable.

In the example below, we show the effect of using the %STR() function when you define a macro variable.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Create a Macro Variable with the CALL SYMPUT Routine

Another way to create a macro variable in SAS is by using the CALL SYMPUT routine. This routine assigns a value produced in a Data Step to a macro variable. Therefore, this method is perfect for creating macro variables from a dataset.

The name of the macro variable is either a text string, a variable name of a SAS dataset, or a character expression that creates a text string. As always, the name of the macro variable must comply with the SAS naming convention.

The value of the macro variable is can be a text string, a number, the name of a variable of a SAS dataset, or a SAS expression.

Below we show the easiest way of using the CALL SYMPUT routine where both the macro variable name and value are a text string.

Although the code above works well, we recommend using the %LET macro statement if you just want to create a simple macro variable. It will save you a lot of code.

Create Macro Variables from a SAS Dataset

The advantage of the CALL SYMPUT routine is that you can create macro variables from a SAS dataset. In other words, you can assign the value of a SAS variable to a macro variable without explicitly specifying the value. This makes your program versatile.

We will use the dataset below to demonstrate this.

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

Normally, you use the DATA statement to create a SAS Dataset. However, to create macro variables from a SAS dataset you need the special DATA _null_ statement.
With the DATA _null_ statement, SAS processes all observations from the input dataset, but it doesn’t create an output dataset.

You execute the SAS code with the RUN statement.

In the example below, we convert the values of the column name into three macro variables (name1, name2, and name3).

Blogs

How to create and use SAS macro functions

What is sas macro. Смотреть фото What is sas macro. Смотреть картинку What is sas macro. Картинка про What is sas macro. Фото What is sas macro

SAS® Macro Language immensely empowers SAS programmers with versatility and efficiency of their code development. It allows SAS users to modularize programming code with “once written – many times used” components, and in many cases automatically generate data-driven SAS code.

Macro language and macro processor

SAS macro language vs. SAS programming language

A SAS program usually consists of two, often interwoven layers – macro layer and non-macro layer, each with its own syntax and its own timing of compilation and execution. In other words, SAS code is a combination of two distinct languages:

The difference between them is like a difference between cooking a meal and eating the meal. In this analogy meal=code, cooking=SAS macro language, eating=SAS programming language. Clear understanding of this difference is the key to becoming a successful SAS programmer.

Two types of SAS macros

There are two distinct types of SAS macros:

What is a SAS macro function?

SAS macro function is a SAS macro that generates a value. In other words, it is the type 2 macro described above. As any SAS macros, SAS macro functions can have any number (zero or more) of positional or/and named parameters (arguments). SAS users may define their own macro functions, but in doing so you may not utilize any SAS language syntax; only SAS macro language syntax is allowed. You can use existing macro functions in your own macro function definition. Among others, one of the most powerful is %SYSFUNC macro function which brings a wealth of SAS language functions into SAS macro language.

Sources of SAS macro functions

SAS macro functions may come from the following three sources.

1. Pre-built macro functions

Pre-built macro functions that are part of the macro processor. These are such macro functions as %eval, %length, %quote, %scan, %str, %sysfunc, %upcase, etc. Here is a complete list of the pre-built SAS macro functions.

2. Auto-call macro functions

Auto-call macros, some of them are type 1 (macros), and some – type 2 (macro functions) such as %cmpres, %left, %lowcase, %trim, %verify, etc. These macro functions supplement the pre-built macro functions. The main difference from the pre-built macro functions is that the auto-call macro functions are program samples of the user-defined macro functions that are written in SAS macro language and made available to you without having to define or include them in your programs. The auto-call macro functions come with your SAS software installation and usually pre-configured for you by setting MAUTOSOURCE and SASAUTOS= macro system options. They may include several macro libraries depending on the SAS products licensed at your site. For example, for my SAS BASE installation the auto-call macro library is in the following folder:

Here is a selected list of auto-call macros provided with SAS software.

From the usage standpoint, you will not notice any difference between the pre-built and the auto-call macro functions. For example, macro function %upcase() is pre-built, while macro function %lowcase() is auto-call macro function. They belong to entirely different families, but we use them as if they are complementary siblings.

3. User-defined macro functions

Finally, there are user-defined macro functions that do not come with SAS installation. These are the macro functions that you define on your own. Usually, they are kept separately from the auto-call macros mainly in order to distinguish them from SAS-supplied ones.

To enable access to your own SAS macro library in addition to the auto-call macro library (or libraries), you can use the INSERT= system option:

options insert=(sasautos="path_to_your_own_macro_library_folder");

Instead of replacing the SASAUTOS value, this option inserts an additional value into the existing SASAUTOS option as the first value, thus allowing you to tap into your own macro library first, and then also into pre-set SAS auto-call libraries.

Creating user-defined macro function

Let’s consider the following example. Suppose, we want to create a macro function that takes a data set name as an argument and returns a value equal to the number of observations in that data set.

We know that the following code calculates the number of observations in a data set:

Can we create a SAS macro function by enclosing this code into macro? Something like this:

The answer is “No”. Yes, we created a valid macro; we can invoke this macro to produce the result:

But this is not a macro function. Remember type 2 macro that does not generate any SAS programming language code, just a value? But this macro does generate SAS code which assigns a value to the macro variable specified as the second argument (result=NOBS).

In order to create a valid macro function, our macro should not have any SAS language code in it – neither a DATA step, nor a PROC step. It may only be comprised of the SAS macro language code. Here it is:

When macro processor executes this macro, the only object that gets passed to the SAS language compiler is the value shown in the line right before the %mend. This is the calculated value of the number of observations (denoted by &n ). This is the only thing that is visible by the SAS language compiler, the rest is the macro language code visible and being handled by SAS macro processor.

IMPORTANT: When defining SAS macro function always use %local statement to list ALL macro variables that are created in your macro to ensure they will not accidentally overwrite same-named macro variables in the calling environment. You don’t need to declare %local for macro parameters as they are always local automatically.

SAS macro functions usage examples

When a macro function is defined this way, wherever you place its invocation %nobs(SASHELP.CARS) in your SAS code it will be evaluated and replaced with the corresponding value (in this case it is number 428) by the SAS macro processor. That way you can avoid substandard hard-coding and make your SAS code dynamic and powerful. You can use macro functions in many SAS coding contexts. For example:

And so on. It’s important to note that arguments (parameters) to macro functions must be either SAS constants or macro expressions resolving to SAS constants. Since macro functions get resolved by the macro processor before SAS program execution, the arguments cannot be variable names. This is the key difference between macro functions and SAS functions.

Your thoughts?

Do you find this post useful? Do you use SAS macro functions? Can you suggest other usage examples? Please share with us in the Comments below.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *