【问题标题】:Elasticity function for lm() coefficientlm() 系数的弹性函数
【发布时间】:2015-03-21 04:23:30
【问题描述】:

我想知道是否有一个函数可以计算用 lm() 估计的模型的(经济)弹性。

因变量在其平均值 Y 附近的百分比变化的弹性,对于自变量在其平均值 X 之上 1% 的变化,计算如下: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)
```

【问题讨论】:

  • This blog post 似乎提供了一些简单的代码。
  • 我看过那篇文章,但就像你说的那样,它只有非常简单的代码来表示两个变量的弹性。均值和系数是使用变量名称单独选择的。我正在处理一个相当大的数据集,并且为所有回归“手动”执行此操作将非常长。所以这就是为什么我认为这里有人可能会带我去......
  • 如果您提供代码以适应我们可以用来编写一些通用代码的简单模型。您应该在您的帖子中包含您想要自动执行此操作的事实。否则,人们可能会提供令您不满意的解决方案。如果您可以包含该示例的预期输出,那就更好了。
  • 我更新了问题并包含了一个示例。希望对您有所帮助。

标签: r lm elasticity


【解决方案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')

```

【讨论】:

    猜你喜欢
    • 2020-03-06
    • 2020-11-28
    • 1970-01-01
    • 2014-02-08
    • 2018-10-03
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 2011-11-23
    相关资源
    最近更新 更多