将字符串替换为 {plm} 模型
Substitute strings into {plm} model
This tutorial 展示了如何将字符串替换为 lm
模型调用。我想做同样的事情,但使用 plm
进行面板回归。目标是制作一个参数组合网格,然后 运行 通过一次 apply
调用进行多次回归,每次都代入适当的变量。
library(plm)
#make grid of parameters to loop over; select just the first row to reproduce the error
parameters <- expand.grid(dv="mpg", x1=c("cyl", "gear"), x2=c("hp", "wt"), stringsAsFactors = FALSE)
row <- parameters[1,]
#lm works
lm(substitute(y ~ x*z, list(y=as.name(row[[1]]), x=as.name(row[[2]]), z=as.name(row[[3]]))), data=mtcars)
#plm does not
plm(substitute(y ~ x*z, list(y=as.name(row[[1]]), x=as.name(row[[2]]), z=as.name(row[[3]]))), data=mtcars)
这产生:
Error: inherits(object, "formula") is not TRUE
解决方案可能涉及将变量名称粘贴到 plm
中,而不是使用 substitute
。或者我可以避免为此目的使用 plm
吗?
plm 需要面板数据。
您可以使用来自 ?plm
.
的 Produc
示例数据集
library(plm)
parameters <- expand.grid(dv="pcap",
x1=c("hwy", "water"),
x2=c("util", "pc"),
stringsAsFactors = FALSE)
row <- parameters[1,]
# I assign the formula to another object
# to avoid clutter in calling plm()
formula.plm <- substitute(y ~ x * z,
list(y = as.name(row[[1]]),
x = as.name(row[[2]]),
z = as.name(row[[3]])))
plm(eval(formula.plm), data = Produc)
This tutorial 展示了如何将字符串替换为 lm
模型调用。我想做同样的事情,但使用 plm
进行面板回归。目标是制作一个参数组合网格,然后 运行 通过一次 apply
调用进行多次回归,每次都代入适当的变量。
library(plm)
#make grid of parameters to loop over; select just the first row to reproduce the error
parameters <- expand.grid(dv="mpg", x1=c("cyl", "gear"), x2=c("hp", "wt"), stringsAsFactors = FALSE)
row <- parameters[1,]
#lm works
lm(substitute(y ~ x*z, list(y=as.name(row[[1]]), x=as.name(row[[2]]), z=as.name(row[[3]]))), data=mtcars)
#plm does not
plm(substitute(y ~ x*z, list(y=as.name(row[[1]]), x=as.name(row[[2]]), z=as.name(row[[3]]))), data=mtcars)
这产生:
Error: inherits(object, "formula") is not TRUE
解决方案可能涉及将变量名称粘贴到 plm
中,而不是使用 substitute
。或者我可以避免为此目的使用 plm
吗?
plm 需要面板数据。
您可以使用来自 ?plm
.
Produc
示例数据集
library(plm)
parameters <- expand.grid(dv="pcap",
x1=c("hwy", "water"),
x2=c("util", "pc"),
stringsAsFactors = FALSE)
row <- parameters[1,]
# I assign the formula to another object
# to avoid clutter in calling plm()
formula.plm <- substitute(y ~ x * z,
list(y = as.name(row[[1]]),
x = as.name(row[[2]]),
z = as.name(row[[3]])))
plm(eval(formula.plm), data = Produc)