-3

I wonder how to use macros in R.

I´m looking for a simple macro so I only need to change for example a date once in a syntax and not on every place where the date is used in the syntax.

In other words like the %let functions in SAS but in R.

  • You're going to have to be (much) more specific if you want a helpful answer. – joran Jun 09 '17 at 15:05
  • you could use an object such as `mydate<- "01/01/2017"` and use that object where you need to change the date. – Andrelrms Jun 09 '17 at 15:06
  • Instead of this DTStamp >= '2017-06-01' – Sven Johansson Jun 09 '17 at 15:06
  • 1
    Put additions and changes to your question in your _question_, not in the comment, please. – joran Jun 09 '17 at 15:08
  • 5
    R is not SAS. R is a programming language, not a macro language. There is no such thing as a "macro" in R. The closest R equivalent of `%let` is the assignment operator `<-`. If you want a single value, you use indices `[ ]`. If you move from SAS to R, you really really really have to let go of the programming logic of the DATA step. R works vastly different. – Joris Meys Jun 09 '17 at 15:18
  • OK, thanks. Tried this, but does not work. date <- '2017-06-01' TD <- sqlQuery(channel, "SELECT * FROM FactStoreSale WHERE DTStamp >= $date " ) – Sven Johansson Jun 09 '17 at 15:46
  • 1
    Often people will use `sprintf` for this: `sprintf("select * from blah where var = %s",date)`. – joran Jun 09 '17 at 15:52
  • like this? sprintf("select * from FactStoreSale where var = %s",date) ? – Sven Johansson Jun 09 '17 at 16:12
  • Yeah, you might want/need quotes around the `%s`. – joran Jun 09 '17 at 16:22
  • Possible duplicate of [How do I use a macro variable in R? (Similar to %LET in SAS)](https://stackoverflow.com/questions/28484072/how-do-i-use-a-macro-variable-in-r-similar-to-let-in-sas) – Jthorpe Jun 09 '17 at 16:55
  • I'm still strugling with this despite all great suggestions... This is how I normaly does it TD <- sqlQuery(channel, "SELECT * FROM sales WHERE date >= '2016-03-27' " ) Now I want to make the date filter dynamic,a date variable 1 year back in time created in R that I can use i an SQLQuery in R. TD <- sqlQuery(channel, "SELECT * FROM sales WHERE date >= ???? " ) – Sven Johansson Jun 12 '17 at 12:35

2 Answers2

1

a closerlook would suggest that creating your own custom function in R and then calling that function would be like a SAS Macro

e.g

myfunction=function(x){ whatever the macro would do pseduo code}

and then call the function

myfunction(var1)

for %let which is a global variable just assign the value to a constant

but overall quit thinking like SAS and switch to object oriented programming in R

Ajay Ohri
  • 3,382
  • 3
  • 30
  • 60
0

Use a constant instead of explicitly writing it out every time?

TaintedQ
  • 11
  • 2