-3

Using R stats, I want to access a variable variable scenario similar to PHP double-dollar-sign technique: http://php.net/manual/en/language.variables.variable.php

Specifically, I am looking for a function in R that is equivalent to $$ in PHP.


UPDATE: The approved answer contains the basic function needed

##################################
    hello="hello world";
    a="hello";
    result=get(a);
    print(result);
##################################

In PHP, I can assign $a="hello"; and $hello="hello world";. I can then use an eval to dynamic change variables; this is called a variables variable in php, using two dollar signs ($$): echo($$a); will print "hello world". It evaluate $a which is hello, then evaluates $hello.

So, I have a regression setup using R, with 4 data options and 3 model options. I perform about 60 lines of stats using R and mainly the library plm, but also tseries, lmtest (a bunch of diagnostic tests, a pooled OLS, fixed effects (FE), and random effects (RE) with tests for heteroskedasticity, serial autocorrelation, cross-dependence autocorrelation, and so on. If these elements exist, I smartly update the standard errors depending on what is present: only hetero [vcovHC white], hetero-serial or hetero-cross [vcovHC arellano], all [vcovSCC Driscoll-Kraay].

In the end, I want to display the adjusted regression models FE/RE for 3 model options on a page. Each page will have one of the four data options. I want to output this in Latex. So in this scenario, I need a variables variable approach. I am trying eval(, parse(, substitute(, assign(.

so consider I have a variable in R mDat.total that contains the data I need for a regression. I also have mDat.hi, mDat.mid, mDat.low. These 4 elements, I can represent as a list of strings pointing to the variable:

d = c("mDat.total","mDat.low","mDat.mid","mDat.hi"); # data loop

Similarly, for the models, I have formula datatypes (using formula,Formula,pForumla such as model.main = emp~wage+capital|lag(wage,1)+capital:

m = c("model.main","model.lone","model.interaction"); # model loop

I want to loop over i in d, j in m, and perform a bunch of regressions.

for(i in 1:length(d))
    {
    myData = $$d[i];
    for j in 1:length(m))
        {
        myModel = $$m[j];
        ... ### do stuff with myData, myModel
            that has been assigned the values of myData (a data frame) 
            and myModel (a model specification)

For i=1;j=1, myData evaluates to be the mDat.total dataframe, and myModel evaluates to be the model.main

Ideally, I want a standalone function using R that behaves like $$ (e.g., in above pseudo code, replace $$ with a function doubleEvaluate(x) or VariableVariable(x).

Thanks in advance.

monte

{x:

0

1 Answer 1

3

Consider using get() to obtain environment variables from string values. Additionally, consider the nested lapply() between dataframe and model lists for more organized returned object. Nested for loops would require appending each iteration into growing list unless you just need to output. Below examples use linear models, lm():

model1 <- y ~ x1
model2 <- y ~ x2
model3 <- y ~ x3

dflist <- c("df1","df2","df3")
modelist <- c("model1", "model2", "model3")

# MODEL DATA RETURNS NESTED LIST OF 3 ELEMENTS 
# EACH WITH CORRESPONDING DATA METRICS (COEFF, RESIDUALS, ETC.)
modeldata <- lapply(dflist,
                    function(x) {                  
                    df<-get(x)       
                    lapply(modelist,
                           function(y) {
                           model <- get(y)
                           ols <- lm(model, df)                                          
                    })                  
               })

# BELOW CREATES MODEL SUMMARY LIST OF 3 ELEMENTS 
# FOR FIRST THREE MODELS USING FIRST DATASET
modelsummary <- lapply(modeldata[[1]], summary)

Example with nested for loop:

# INITIALIZE A LIST TO CONTAIN DATA
modeldata <- list()

for (i in dflist){  
  df<-get(i)
  for (j in modelist){    
    model <- get(j)

    # APPEND TO MODELDATA LIST
    # FINAL RETURN IS LARGE LIST OF ALL DATA MODELS
    modeldata <- c(modeldata, lm(model, df))    
  }  
}
Sign up to request clarification or add additional context in comments.

8 Comments

Nice answer. Yes, I concur that lapply is a correct approach, but there are times the logic of lapply doesn't make as much sense as a procedural for-loop. But, you are probably right about the growing list. Let me code this and see if it works. I am almost positive I can get this to work, but for any variable type, is there a $$ approach that can work with R?
So in your scenario, you are building only one object (e.g. ols). I need to perform several calls, and store in a master list... I tried replacing your line <code>ols <- lm(model, df)</code> with a bunch of calls, and finish with a list statement <code>list(unittest.1=unittest.1, unittest.2=unittest.2, bptest=bptest, viftest=viftest, pdwtest=pdwtest, pbgtest=pbgtest, pooled.reg=pooled.reg, pooled.sum=pooled.sum, pooled.xsd=pooled.xsd, pooled.coef=pooled.coef, fixed.reg=fixed.reg, ..., random.reg=random.reg, ..., hausmantest=hausmantest);</code>
In the list scenario above, it returns an object of the correct dimensionality, but all values are FALSE.
> str(modeldata) List of 4 $ :List of 3 ..$ : logi FALSE ..$ : logi FALSE ..$ : logi FALSE $ :List of 3 ..$ : logi FALSE ..$ : logi FALSE ..$ : logi FALSE $ :List of 3 ..$ : logi FALSE ..$ : logi FALSE ..$ : logi FALSE $ :List of 3 ..$ : logi FALSE ..$ : logi FALSE ..$ : logi FALSE
I probably needed "quotes" ... <code>list("unittest.1"=unittest.1, "unittest.2"=unittest.2, "bptest"=bptest, "viftest"=viftest, "pdwtest"=pdwtest, "pbgtest"=pbgtest, "pooled.reg"=pooled.reg, "pooled.sum"=pooled.sum, "pooled.xsd"=pooled.xsd, "pooled.coef"=pooled.coef, "fixed.reg"=fixed.reg, ..., "random.reg"=random.reg, ..., "hausmantest"=hausmantest);</code>
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.