首页 > 解决方案 > 如何在r中的嵌套公式中处理字符串变量名

问题描述

我正在尝试使用变量名称列表运行loop回归lm。请看下面的代码。

order <- c(4, 6, 8, 10, 12, 14, 16) # position of variables in my data frame

for(i in order) {
  m7 <- df %>% filter(names(df)[i] > 0) %>% 
    pdata.frame(index=c("index","Year")) %>% 
    plm(formula= log(names(df)[i]) ~ log(names(df)[i-1]) + 
          frez + log(dd) + I((log(dd))^2) + 
          preci + I(preci^2) + 
          + m7 + max.c + spei + lt + qt, 
        data=., effect = c("individual"),model = "within") %>% 
    coeftest(., vcov = function(x) vcovHC(x, method = 'arellano', cluster = 'group', type = 'HC3'))
}

我收到一条错误消息。我想问题可能出在log.

Error in log(names(df)[i]) : non-numeric argument to mathematical function

我的变量名是

> names(df)
 [1] "index"           "Year"            "barley_harv"     "barley_yield"    "cotton_harv"     "cotton_yield"   
 [7] "oat_harv"        "oat_yield"       "peanut_harv"     "peanut_yield"    "rice_harv"       "rice_yield"     
[13] "sorghum_harv"    "sorghum_yield"   "sunflower_harv"  "sunflower_yield" "AOT40"           "frez"           
[19] "dd"              "spei"            "m7"              "max.c"           "preci"           "SUM60"          
[25] "W126"            "lt"              "qt"  

任何想法我应该如何解决这个问题???

标签: rformula

解决方案


类似(代码片段):

## .. outside
other_vars <- c("frez","log(dd)", "I((log(dd))^2)", 
                "preci", "I(preci^2)", 
                "m7","max.c","spei","lt","qt")
## ... inside loop ...
ff <- reformulate(c(sprintf("log(%s)",names(df)[i-1]),other_vars),
                  response=sprintf("log(%s)",names(df)[i]))
m7 <- (df 
         %>% filter(names(df)[i] > 0) 
         %>% pdata.frame(index=c("index","Year")) 
         %>% plm(formula= ff, data=., effect = c("individual"),
            model = "within") 
         ## ... coeftest stuff here
      )

推荐阅读