Questions tagged [stata-macros]
38 questions
0
votes
0
answer
4
Views
Loop strmatch, then dataset intersection, then extract data subset by observation
Step 1: Find intersection between two datasets. I would like to find the intersection between biglist and matchlist.
use matchlist, clear //matchlist contains unique observations that I need
levelsof countryname, local(country1)
use biglist, clear //big list has a lot of duplicates and things I don'...
1
votes
1
answer
127
Views
How do I reference a data file with a macro?
I have various Stata data files. These are located in different folders. I also have a single do file that uses these files, one at a time.
Is there a way to use a macro to reference a particular dataset in my do file?
For example:
local datafile = "C:\filepath\mydata.dta"
The idea is to use this l...
1
votes
1
answer
141
Views
Adding time in a file name
Consider the code snippet below:
local date: display %td_CCYY_NN_DD date(c(current_date), "DMY")
local date_string = subinstr(trim("`date'"), " " , "", .)
save "`date_string'_example", replace
mkdir "`date_string'_example"
This creates output as follows:
20170521_example.dta
However, I want to creat...
2
votes
2
answer
41
Views
Extract regression results with names of covariates
I would like to run linear regressions using a categorical exposure variable and to output the results to an excel sheet with the names of each covariate included next to their results.
The Stata code below works fine to export the results:
sysuse auto.dta, clear
describe
summ
postfile temp str40...
1
votes
1
answer
1.9k
Views
“word # of string” idiom (part of extended string functions)
I'm trying to label variables in a forvalues loop on Stata version 11.2.
However, I can't get the extended string function word # of string idiom to work:
local names `""Growth" "Mature" "All""'
forvalues i = 0/2 {
local name : word `i' of `names'
display "`name'"
}
This follows a Statalist solution...
1
votes
2
answer
4.6k
Views
How to store a mean value in a local macro and then save it in another file?
I have a Stata file file1.dta and one of the variables is income. I need to calculate average_income, assign it to a local macro, and store in a different Stata file, New.dta.
I have tried the following in a do file:
#delimit;
clear;
set mem 700m;
use file1.dta;
local average_income = mean income;...
6
votes
5
answer
27.4k
Views
Tabulate multiple variables with common prefix using a local macro
I have a number of variables whose name begins with the prefix indoor. What comes after indoor is not numeric (that would make everything simpler).
I would like a tabulation for each of these variables.
My code is the following:
local indoor indoor*
foreach i of local indoor {
tab `i' group, c...
0
votes
1
answer
13
Views
Different cases of variable name after append
I have appended multiple files into a single sSata dataset. It has now 335 variable names. Some variable names have casing issues like almirah and ALMIRAH storing the same information from different datasets.
I am replacing these variables like this one by one:
count if mi(almirah)
local first=r(N)...
11
votes
2
answer
349
Views
Equivalent of Stata macros in Python
I am trying to use Python for statistical analysis.
In Stata I can define local macros and expand them as necessary:
program define reg2
syntax varlist(min=1 max=1), indepvars(string) results(string)
if "`results'" == "y" {
reg `varlist' `indepvars'
}
if "`results'" == "n" {
qui reg `varlist' `inde...
6
votes
2
answer
266
Views
How do I create a “macro” for regressors in R?
For long and repeating models I want to create a "macro" (so called in Stata and there accomplished with global var1 var2 ...) which contains the regressors of the model formula.
For example from
library(car)
lm(income ~ education + prestige, data = Duncan)
I want something like:
regressors
2
votes
3
answer
447
Views
Macro equivalent of Stata [duplicate]
This question already has an answer here:
R equivalent of Stata local or global macros
3 answers
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...
3
votes
4
answer
1.4k
Views
R equivalent of Stata's for-loop over local macro list of stubnames
I'm a Stata user that's transitioning to R and there's one Stata crutch that I find hard to give up. This is because I don't know how to do the equivalent with R's "apply" functions.
In Stata, I often generate a local macro list of stubnames and then loop over that list, calling on variables whose...
2
votes
1
answer
693
Views
Comparing elements of two different local macros
I have a local macro called peer_list that contains 280 distinct elements, all of which are strings. I also have another local macro called used_list that contains a subset of the elements contained in the local peer_list.
For each element in peer_list I would like to test whether that element is...
2
votes
1
answer
1k
Views
When are global macros deleted?
I have a do file from which I would like to select a few lines of code and then run them using the Execute (do) button. The problem is that there are a bunch of local macros defined in this do file. I can run them, but then in the Stata command prompt the local macros are not accessible. Thus, I th...
2
votes
3
answer
5.5k
Views
Storing values in a macro variable
I'm using the levelsof command to identify unique values of a variable and stick them into a macro. Then later on I'd like to use those values in the macro to select records from another dataset that I'll load.
What i have in mind is something along the following lines:
keep if inlist(variable, "...
3
votes
1
answer
57
Views
Creating a loop using local macros fails
I tried creating a forvalues loop using local macros:
local open forval i=1/10 {
local close }
`open'
di `i'
`close'
However, I get the following error:
forval command may not result from a macro expansion interactively or in do files
r(198);
What am I doing wrong?
4
votes
5
answer
21.4k
Views
How to rename many variables with string suffixes
In Stata, I have a set of variables that all begin with pkg. In their current state, their endings are numeric: pkg1, pkg2, pkg3, pkg4 and so on.
I need to change all of these variables' endings to strings: pkgmz, pkggmz, pkgsp, pkgsptc etc.
I have a column of these string endings, which I can de...
2
votes
2
answer
1k
Views
How to manipulate filenames with a macro
I want to save the results of my Stata forvalues loop into individual files. One component of the filename should be the value j assigned to the macro within a forvalues loop.
Apparently my code leads to an instruction always to save with 1995. As such, I get messages telling me that this file alre...
1
votes
2
answer
130
Views
Automated labeling of logarithmic plots
I would like to automate the graph axis values for a series of plots in Stata 13.
In particular, I would like to show axis labels like 10^-1, 0, 10^1, 10^2 etc. by feeding the axis options macros.
The solution in the following blog post gives a good starting point:
Labeling logarithmic axes in Stat...
2
votes
1
answer
140
Views
Append local macro in Stata
In Stata, I want to explore regressions with many combinations of different dependent and independent variables.
For this, I decided to use a loop that does all these regressions, and then saves the relevant results (coefficients, R2, etc.) in a matrix in a concise and convenient form.
For this matr...
1
votes
2
answer
79
Views
Keep a list of variables when some variables don't exist
For several countries, I have one dataset and I want to keep a list of variables (specified in a global vlist) for each of them. Some variables do not exist in some countries.
I want Stata to ignore the non-existence of these variables and execute the keep command for the rest of the variables. How...
2
votes
4
answer
284
Views
What types of languages allow programmatic creation of variable names?
This question comes purely out of intellectual curiosity.
Having browsed the Python section relatively often, I've seen a number of questions similar to this, where someone is asking for a programmatic way to define global variables. Some of them are aware of the pitfalls of exec, others aren't.
H...
1
votes
4
answer
483
Views
Using regular expressions or subinstr() to clean local macros
My aim is to clean a given local from _ and all numbers following the underscore at the end of the words. Assume that I have underscores followed by numbers at the end of the words only.
By using subinstr(), I am able to specify that I want to eliminate _1 (and possibly loop over different numbers),...
2
votes
1
answer
52
Views
Is it possible to make Stata throw an error by default when a global macro is not defined, instead of a missing string?
A feature of Stata that is sometimes inconvenient is that calling a non-defined macro returns the missing value . [edit: Stata actually returns a missing string "", not a numerical missing value], instead of throwing an error.
A piece of code, whose correct execution requires the definition of the...
1
votes
5
answer
131
Views
Replace a subset of data with a sequence of integers
I have a dataset that looks like the following:
id test
1 A
2 A
3 A
. B
. B
. B
I would like to fill in the missing values with a sequence of integers corresponding to their id:
id test
1 A
2 A
3 A
1 B
2 B
3 B
I initially thought about using a fo...
2
votes
1
answer
173
Views
How to separate Stata macro `varlist' with commas for using in mi( ) and inlist( )?
I want to store a list of variables in a macro and then call that macro inside a mi() statement. The original application is for a programme that uses data I cannot bring online for secrecy reasons, and which will include the following statement:
generate u = cond(mi(`vars'),., runiform(0,1))
The i...
2
votes
1
answer
85
Views
Bring R list into Stata as macro?
I wish to run a Lasso model in R from Stata and then bring a resulting character list (the names of the subset coefficients) back into Stata as a macro (for example, a global).
At the moment I am aware of two options:
I save a dta file and run an R script from Stata using shell:
shell $Rloc --vanil...
4
votes
1
answer
3.5k
Views
How to keep a list of variables given some of them may not exist?
I have 100 dta files. I have a list of variables that I need to keep and save temporary copies on the fly. Some variables may or may not exist in a certain dta.
I need Stata to keep all variables that exist in a dta and ignore those that do not exist.
The following code has wrong syntax, but it co...
2
votes
2
answer
60
Views
Assign value to local variable with if-statement
I'm trying to assign a conditional value to a local macro variable in Stata 15.
I have a local variable that only can have two values; "o" or "u". Then I have another local variable that I want to get the other letter of these two than the first local variable.
My code looks like this:
local utr o...
8
votes
2
answer
4.3k
Views
Stata: Check if a local macro is undefined
I am writing a Stata do file and I would like to provide default values if the user does not supply some parameters. To do so, I woud like to check if a macro is undefined.
I have come up with a hacky way to do this:
*** For a local macro with the name value:
if `value'1 != 1 {
...do stuff
}
But I...
1
votes
2
answer
32
Views
Find union of two variable-name scalars
I have a Stata program that outputs a local scalar of space-separated variable names.
I have to run the program twice on two samples (same dta) and store the union (intersection - variable names appearing in both scalars) as a new space-separated local scalar (for input to another program).
I can'...
2
votes
1
answer
775
Views
How to extract unique strings from a macro?
I'm trying to automate a reshape using Stata.
I have a series of variables measured yearly. They are all named varname_yy, where yy is a number referring to the year of measurement. I managed to extract all the stubs varname_ from the variables and to put them into a macro using the following code:...
1
votes
2
answer
34
Views
Generating values for columns between a range
I have the following dataset
A B begin_yr end_yr
asset brown 2007 2010
asset blue 2008 2008
basics caramel 2015 2015
cows dork 2004 2006
I want A and B to have rows for each year represented.
I expanded for each year:
gen...
1
votes
1
answer
1.7k
Views
Using do-file with local macro
I am getting the following error in Stata while using a do file with a local macro:
clear
capture log close
sysuse auto,clear
log using stata,text replace
local varlist price mpg rep78 weight length
reg 'varlist'
local close
Output
local varlist price mpg rep78 weight length
reg 'varlist'
invali...
5
votes
3
answer
3.8k
Views
R equivalent of Stata local or global macros
I am a Stata user trying to learn R.
I have a couple of lengthy folder paths which, in my Stata code, I stored as local macros. I have multiple files in both those folders to use in my analysis.
I know, in R, I can change the working directory each time I want to refer to a file in one of the fold...
1
votes
2
answer
576
Views
Local macros for subset of observations
I would like to create a local macro for a subset of my dataset to use for future regressions (see Some Uses for Macros Outside of Loops section).
I've started off with code that is along the following lines:
quietly reg y x1 x2 x3
local subset if e(sample)
list Unit `subset'
reg y x1 x2 if `subse...
2
votes
2
answer
66
Views
Generate a new macro prefixing words of an old macro
Define a macro try:
local try "a b c"
This will generate a macro with the value a b c.
Now I want a new macro try2 which takes the value da db dc. That is, I want to add the same prefix to each element of the old macro and define it as a new macro.
2
votes
2
answer
220
Views
Multiple local in foreach command macro
I have a dataset with multiple subgroups (variable economist) and dates (variable temps99).
I want to run a tabsplit command that does not accept bysort or by prefixes. So I created a macro to apply my tabsplit command to each of my subgroups within my data.
For example:
levelsof economist, local(l...