Chris L
Chris L

Reputation: 338

How do I use a macro variable in R? (Similar to %LET in SAS)

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!

Upvotes: 8

Views: 29578

Answers (3)

Konrad Rudolph
Konrad Rudolph

Reputation: 545528

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.

Upvotes: 21

Andy
Andy

Reputation: 1

None of them works. The macro variable is invoked with & in SAS but no similar & being used in R although you can use new=as.name("f3") or new=quote(f3) to refer to f3 as shown below.

> test<-data.frame(f1=c(1,2), f2=c("a","b")); test
#   f1 f2
#1  1  a
#2  2  b

> new=as.name("f3"); new; 
#f3
> new=quote(f3); new; 
#f3

> # you still get new rather than f3 as expected
> new<-test$f1; 
> new
#[1] 1 2

Upvotes: -5

Jthorpe
Jthorpe

Reputation: 10167

how about this:

reg<-lm(formula(paste(depvar ,'~  var1 + var2')), data=mydata)

Upvotes: 8

Related Questions