使用R,如何在PHP中引用变量变量(或变量变量) [英] Using R, how to reference variable variables (or variables variable) a la PHP

查看:1064
本文介绍了使用R,如何在PHP中引用变量变量(或变量变量)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用R统计信息,我想访问类似于PHP双美元符号技术的可变变量方案: http://php.net/manual/en/language.variables.variable.php

具体地说,我正在R中寻找一个与PHP中的$$相等效的函数.


更新:批准的答案包含所需的基本功能

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


在PHP中,我可以分配$a="hello";$hello="hello world";.然后,我可以使用eval动态更改变量.这在php中称为变量变量,使用两个美元符号($$):echo($$a);将显示"hello world".它将计算$ a,这是您好,然后计算$ hello.

因此,我有一个使用R的回归设置,具有4个数据选项和3个模型选项.我使用R和主要执行库plm来执行大约60行统计,还使用tseries,lmtest(一堆诊断测试,汇总的OLS,固定效应(FE)和随机效应(RE))进行异方差性,串行自相关性测试,交叉相关的自相关等等,如果存在这些元素,我会根据存在的内容巧妙地更新标准错误:仅异源[vcovHC白色],异序列或异源交叉[vcovHC arellano],所有[vcovSCC Driscoll -Kraay].

最后,我想在页面上显示3个模型选项的调整后的回归模型FE/RE.每个页面将具有四个数据选项之一.我想在Latex中输出它.因此,在这种情况下,我需要一个变量变量方法.我正在尝试eval(parse(substitute(assign(.

所以考虑我在R mDat.total中有一个变量,其中包含我需要回归的数据.我也有mDat.himDat.midmDat.low.我可以将这4个元素表示为指向变量的字符串列表:

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

类似地,对于模型,我具有公式数据类型(使用公式,Formula,pForumla,例如model.main = emp~wage+capital|lag(wage,1)+capital:

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

我想在d中循环遍历i,在m中循环遍历j,并执行一堆回归.

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)

对于i=1;j=1,myData评估为mDat.total数据帧,而myModel评估为model.main

理想情况下,我希望使用R的独立函数,其行为类似于$$(例如,在上述伪代码中,将$$替换为doubleEvaluate(x)或VariableVariable(x)函数.

谢谢.

monte

{x:

解决方案

考虑使用 get()从字符串值获取环境变量.此外,请考虑在数据框和模型列表之间嵌套的lapply(),以获得更有条理的返回对象.嵌套的for循环将需要将每个迭代附加到增长列表中,除非您只需要输出.以下示例使用线性模型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)

带有嵌套for循环的示例:

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

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:

解决方案

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

这篇关于使用R,如何在PHP中引用变量变量(或变量变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆