我想知道是否有一个函数可以计算用lm()估算的模型的(经济)弹性。
因变量百分比变化的弹性,在其平均值Y附近,对于自变量中1%的变化,高于其平均值X,计算如下:b * X / Y(b =模型系数为自变量)。
下面是具有简单线性模型的Rmd文件的代码和每个系数的弹性。输出应该是变量名称和弹性的表格。
---
title: "Elasticity"
output: html_document
---
```{r}
N <- 1000
u <- rnorm(N)
x1 <- rnorm(N)
x2 <- 1 + x1 + rnorm(N)
y <- 1 + x1 + x2 + u
df <- data.frame(y,x1,x2)
fit <- lm(y ~ x1 + x2, data = df)
elax1 <- as.numeric(fit$coefficients["x1"] * mean(df$x1)/mean(df$y))
elax2 <- as.numeric(fit$coefficients["x2"] * mean(df$x2)/mean(df$y))
variable <-c ('x1','x2')
elasticity <-c (elax1,elax2)
a <- data.frame(variable,elasticity)
```
Output the results in a table:
```{r, message=FALSE,results='asis'}
require(stargazer)
stargazer(a, summary = FALSE,type = 'html',rownames=FALSE)
```
答案 0 :(得分:1)
我提出了自己的解决方案,也许它可以帮助别人。请注意,我在模型中包含了一个交互。当然,欢迎改进。
---
title: "Elasticity"
output: html_document
---
Generate data and linear model:
```{r}
N <- 1000
u <- rnorm(N)
x1 <- rnorm(N)
x2 <- 1 + x1 + rnorm(N)
y <- 1 + x1 + x2 + u
df <- data.frame(y,x1,x2)
fit <- lm(y ~ x1 * x2, data = df)
```
Function to calculate elasticities:
```{r,results='asis'}
elasticities <- function(linmod){
Ncoef <- nrow(data.frame(linmod$coefficients))
for(i in 2:Ncoef){
el <- as.numeric(linmod$coefficients[i] * colMeans(model.matrix(linmod))[i]/colMeans(model.matrix(linmod))[1])
ifelse (i== 2, elasticity <- el, elasticity <- rbind(elasticity,el))
}
rownames(elasticity) <- names(coef(linmod)[-1])
colnames(elasticity) <- 'elasticities'
return(data.frame(elasticity))
}
```
Run the elasticites function and produce a nice table:
```{r,results='asis',message=FALSE}
a <- elasticities(fit)
require(stargazer)
stargazer(a, summary = FALSE, type = 'html')
```