3

I am an R enthusiast struggling the land of Stata. I have encountered the following problem in my attempts to "translate" from R to Stata:

In R, so that my script files don't get too big and crazy I like to write them in smaller parts and then have one main R script that reads in the smaller ones e.g.

  1. source("script-1.R")
  2. code blah1
  3. code blah2
  4. source("script-2.R") etc......

I would like to do the same thing in Stata and have tried doing

  1. do "script-1.do"
  2. code blah1
  3. code blah2
  4. do "script-2.do" etc......

However, I find that if I create a macro in script-1.do e.g. local bird 1 The object/macro bird is not accessible in the main script or accessible to script-2.do. If I try to display the contents of bird in the main script, it's just empty.

Why is this? Any advice?

4

2 回答 2

7

Try using include. You can read about the differences between include and do (or run) here:

. help include

于 2012-04-24T16:57:15.523 回答
6

Stata macros fall into two groups: local and global. The local ones only exist in the process in which they were defined (which can be an interactive session, do-file, or a program). If you defined something in script-1.do, it will only exist there, and you would have to explicitly return it to be visible elsewhere. (Do-files cannot really do that though; you'd have to define a program, rclass to return values, and breaking the chunks of code into programs is a good practice.) Avoid global macros unless absolutely, unavoidably necessary.

R has some control over the scope of its objects, but it isn't nearly any good compared to Stata's control over the macros. The variables and the data set are still global in Stata, and you cannot have more than one data set at a time. One other thing you will be pleasantly surprised with Stata is parameter passing by reference, which saves a lot of memory as compared to R's passing by value. So different packages have different strengths, and it would be short-sighted to say that one is better than the other.

Having said that, Keith's suggestion to use include is right on spot. I just tried to explain the "why" part of your question. Also, if what you need to exchange between the programs is a number, you can store it in an explicitly named scalar that will be visible to all processes.

于 2012-07-12T14:54:08.233 回答