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

How to assign a macro to 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'm struggling to do something like this (this doesn't work)

 depvar <<- sales_ind reg<-lm(depvar ~ var1 + var2, data=mydata) 

Any ideas?

Thanks!

+5
source share
3 answers

how about this:

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

Let me introduce an alternative solution, because there is no need to go in a conceptual workaround through character strings that need to be analyzed:

R allows you to manipulate expressions at run time (without encoding them as strings, that is), using a set of functions such as substitute or bquote . bquote is probably closest to the SAS approach:

 depvar = quote(sales.int) reg = lm(bquote(.(depvar) ~ var1 + var2), mydata) 

bquote essentially takes an R expression and replaces each variable that is surrounded by a value .(…) by its value. The first line gives the name of the variable - this is very similar to the actual macro in SAS. This should be surrounded by quote , because otherwise R will try to assign the contents of sales.int depvar and not its name. quote works identically to bquote , except that you cannot use the syntax .(…) in it to replace existing variables.

You can also determine this name from user input (i.e., from a character string using as.name :

 depvar = as.name('sales.int') 

as.name converts a character string to an object name R.


Just a comment on language design, as this is a common misunderstanding: R may be less intuitive than SAS in this regard, but it is conceptually much more consistent and generally applicable. Statistical packages other than R essentially provide hacks for working on the language, while R integrates formulas perfectly into the language.

+13
source

None of them work. The macro variable is called with and in SAS, but is not similar and is 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 
-1
source

Source: https://habr.com/ru/post/1213263/


All Articles