How do I assign a macro variable in R?
In SAS, I would use the following code
%LET DEPVAR = sales_ind
PROC REG DATA=mydata;
MODEL &DEPVAR = VAR1 + VAR2;
RUN;
However, in R, I am struggling to do something similar (this doesn't work)
depvar <<- sales_ind
reg<-lm(depvar ~ var1 + var2, data=mydata)
Any ideas?
Thank you!
Although you cannot use macros in R, R offers other features like functions and loops that can perform the same tasks as SAS macros.
After a macro variable is created, you typically use the variable by referencing it with an ampersand preceding its name (&variable-name), which is called a macro variable reference. These references perform symbolic substitutions when they resolve to their value. You can use these references anywhere in a SAS program.
Knowing how to create and use macro variables is the first step in learning the SAS Macro Language. One of the primary techniques is through the %LET statement. Other ways of creating macro variables includes the use of the iterative %DO loop, macro parameters, the SQL INTO: clause, and the DATA step SYMPUT routine.
You can use %LET to create a macro variable containing a character string. You can use CALL SYMPUT if you want to store the value of a given variable rather than a character string. A third way is to use a SELECT statement together with an INTO option within PROC SQL.
Let me provide an alternative solution, because there’s no need to go the conceptual detour via character strings which have to be parsed:
R allows you to manipulate expressions at runtime (without encoding them as strings, that is), via a set of functions such as substitute
or bquote
. bquote
probably comes closest to the SAS approach:
depvar = quote(sales.int)
reg = lm(bquote(.(depvar) ~ var1 + var2), mydata)
bquote
essentially takes an R expression, and replaces every variable which is surrounded by .(…)
by its value. The first line assigns a name to a variable – this is very similar to the actual macro in SAS. This needs to be surrounded by quote
, because otherwise R would try to assign the contents of sales.int
to depvar
, rather than its name. quote
works identical to bquote
, except that you cannot use the .(…)
syntax in it to replace existing variables.
You can also determine this name from a user input (i.e. from a character string, by using as.name
:
depvar = as.name('sales.int')
as.name
converts a character string to an R object name.
Just a comment on the language design, since this a common misunderstanding: R may be less intuitive than SAS in this regard, but it‘s conceptually much more consistent and generally applicable. Non-R statistics packages essentially provide hacks to work around the language while R integrates formulae beautifully into the language itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With