简体   繁体   English

用R绘制预测值并比较随机效应plm模型中的相互作用项的最佳方法是什么?

[英]What is the best way in R to plot predicted values and compare interaction terms in a random effects plm model?

I have a plm random effects model that includes an interaction between a continuous and a categorical variable (for illustrative purposes, let's say the categorical variable is strong religiosity and the continuous is contribution to charity). 我有一个plm随机效应模型,该模型包括连续变量和分类变量之间的相互作用(出于说明目的,假设分类变量具有很强的宗教信仰,而连续变量则是对慈善事业的贡献)。

Here is sample data (IRL, data much larger) 这是示例数据(IRL,数据大得多)

ratio     contrib     relig    np_score     ID    year 
.4          3          1          11        1      1990  
0           7          0          8         2      1990
.9          7          1          6         1      1992
.7          6          1          10        1      1994
.1          2          0          4         2      1992
.3          9          0          8         2      1994

I want to plot the predicted outcomes as contribution increases depending on whether the respondent does or does not identify as strongly religious. 我想随着贡献的增加来绘制预期的结果,这取决于受访者是否认同强烈的宗教信仰。

m1 <- plm(ratio ~ contrib + relig + np_score + contrib*relig, 
            data = panel_dat, 
            index = c("ID", "year"),
            model = "random", random.method = "amemiya")

I have tried interaction.plot as follows: 我已经尝试了interaction.plot,如下所示:

interaction.plot(panel_dat$contrib, panel_dat$relig, predict(m1), col = 2:3, lty = 1)

But I get the error term: 但是我得到了错误术语:

Error in tapply(response, list(x.factor, trace.factor), fun) : 
  arguments must have same length

I would ultimately rather do this with ggplot2. 我最终宁愿使用ggplot2做到这一点。 Any suggestions? 有什么建议么? Seems like there should be a simple answer... 似乎应该有一个简单的答案...

This sample code produces the multiline plot below (in ggplot). 此示例代码生成下面的多线图(在ggplot中)。 Not sure if the axes are correct ... you can adjust as needed. 不确定轴是否正确...您可以根据需要进行调整。

# Create sample dataframe
df <- data.frame(
  id = c(1, 1, 1, 2, 2, 2),
  year = c(2000, 2001, 2002, 2000, 2001, 2002),  
  ratio = c(0.3, 0.6, 0.1, 0.4, 0.5, 0.6),
  contrib = c(310, 220, 230, 140, 0, 10),
  relig = c(1, 1, 1, 3, 3, 3)
)

# Build model and predictions
library(plm)
m1 <- plm(ratio ~ contrib + relig + contrib*relig, data = df, index = c('id','year'))
df$p_ratio <- predict(m1)

# Create plot
library(ggplot2)
ggplot(data=df, aes(x=contrib, y=p_ratio, group=relig))+geom_line(size=2, aes(color=relig))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM