Rob Hall
Rob Hall

Reputation: 1418

Stata: extract p-values and save them in a list

This may be a trivial question, but as an R user coming to Stata I have so far failed to find the correct Google terms to find the answer. I want to do the following steps:

So I am wondering how to extract p-values (or similar) from command results and how to save them into a vector-like object that I can work with. Here is some R code that does something similar:

myData <- data.frame(a=rnorm(10), b=rnorm(10), c=rnorm(10)) ## generate some data
pValue <- c()
for (variableName in c("b", "c")) {
    myModel <- lm(as.formula(paste("a ~", variableName)), data=myData) ## fit model
    pValue <- c(pValue, coef(summary(myModel))[2, "Pr(>|t|)"]) ## extract p-value and save in vector
}
pValue * 2 ## do amazing multiple comparison correction

To me it seems like Stata has much less of a 'programming' mindset to it than R. If you have any general Stata literature recommendations for an R user who can program, that would also be appreciated.

Upvotes: 0

Views: 6741

Answers (1)

Michael Kaiser
Michael Kaiser

Reputation: 133

Here is an approach that would save the p-values in a matrix and then you can manipulate the matrix, maybe using Mata or standard matrix manipulation in Stata.

matrix storeMyP = J(2, 1, .)  //create empty matrix with 2 (as many variables as we are looping over) rows, 1 column
matrix list storeMyP  //look at the matrix

loc n = 0 //count the iterations

foreach variableName of varlist b c {

  loc n = `n' + 1  //each iteration, adjust the count

  reg a `variableName'
  test `variableName' //this does an F-test, but for one variable it's equivalent to a t-test (check: -help test- there is lots this can do
  matrix storeMyP[`n', 1] = `r(p)'  //save the p-value in the matrix 

}
matrix list storeMyP  //look at your p-values 
matrix storeMyP_2 = 2*storeMyP //replicating your example above 

What's going on this that Stata automatically stores certain quantities after estimation and test commands. When the help files say this command stores the following values in r(), you refer to them in single quotes. It could also be interesting for you to convert the matrix column(s) into variables using svmat storeMyP, or see help svmat for more info.

Upvotes: 2

Related Questions