2

Can macros be used in R?

I did look another question similar to this one, but couldn't understand it well.

Let's say I want to create scalars, each with a different name and content. Basically, what I want to run in R can be illustrated by the following dummy example:

local i=1
forvalues i=1/5 {
    scalar scalar_`i'=`i'+1
}

In Stata, as i takes different values, scalar1, scalar2, scalar3 etc. are generated. I didn't have to type out the entire list (just i=1/5) while running the loop.

Can this be done in R?

PGupta
  • 183
  • 1
  • 7
  • Best to give links, not allusions: http://stackoverflow.com/questions/15691390/r-equivalent-of-stata-local-or-global-macros – Nick Cox Oct 22 '13 at 07:50

3 Answers3

9

You can do that in R, as shown by @geektrader's answer. But you (probably) don't want to -- handling variables by string manipulations of their names is a bad idea for a lot of reasons. Instead you want to do this:

scalar<-2:6

This creates an array called scalar, with the values 2 through 6, which you can then access like this:

> scalar[1]
[1] 2
> scalar[2]
[1] 3
> scalar[3:5]
[1] 4 5 6
mrip
  • 14,913
  • 4
  • 40
  • 58
  • +1 Handling variables by string manipulations of their names is bad idea in almost any of the languages. – CHP Oct 22 '13 at 06:07
5

R is a programming language. So you can do much more than what "macros" do in other statistical packages.

As for your question, you can use assign function

for ( i in 1:5) { assign(paste0('scalar_', i), i+1) }
CHP
  • 16,981
  • 4
  • 38
  • 57
5

This question can, I hope, be answered without polemics or unnecessary assertions about what is bad programming style. String handling is natural and central to many languages.

In Stata too, what you want is well thought of as a vector and naturally handled as such. The name scalar is not a good name for a scalar.

R and Stata are different languages with some common roots in Unix and Unix-based languages, but they have evolved separately. Often what is idiomatic and natural in one language is not idiomatic and natural in the other language. As a first approximation it is best to follow the style of experienced users.

Nick Cox
  • 35,529
  • 6
  • 31
  • 47