[Solved] Using R, how to reference variable variables (or variables variable) a la PHP


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))    
  }  
}

8

solved Using R, how to reference variable variables (or variables variable) a la PHP