我正在尝试将Stata边距图复制到R
,但是即使在浏览StackExchange并试图弄清楚它几周后也无法这样做。
您是否碰巧知道如何在R
中重新创建使用边距图创建的地图?
首先,我使用以下R
代码生成了可重现的数据集:
set.seed(96)
sampleData <- data.frame(
ID = 1:200,
outcome = sample(1:7, 200, replace = T),
scale = sample(1:7, 200, replace = T),
dummy1 = sample(0:1, 200, replace = T),
dummy2 = sample(0:1, 200, replace = T))
write.dta(dataframe, "sampledata.dta")
然后,我将数据读入Stata
并运行以下命令以获取附图:
reg outcome dummy1##c.scale dummy2##c.scale
margins dummy1 dummy2, at(scale=(1(1)7))
marginsplot, recast(line) name(outcome, replace)
基本上,当这个代码在Stata中运行时,我得到了我试图在R中复制的图:
您是否有任何可以帮助我复制此图表的指针?
答案 0 :(得分:3)
# your data
set.seed(96)
sampleData <- data.frame(
ID = 1:200,
outcome = sample(1:7, 200, replace = T),
scale = sample(1:7, 200, replace = T),
dummy1 = sample(0:1, 200, replace = T),
dummy2 = sample(0:1, 200, replace = T))
# all possible combinations
newData <- data.frame(scale=rep(1:7, each=4),
dummy1=rep(c(0, 0, 1, 1), 7),
dummy2=rep(0:1, 2*7))
newData$dummy <- paste(newData$dummy1, newData$dummy2)
a <- lm(outcome ~ dummy1*scale + dummy2*scale, data=sampleData)
b <- predict(a, newdata=newData, interval="confidence")
c <- cbind(newData, b)
require(ggplot2)
# one pane
d <- ggplot(c, aes(scale, fit, color=dummy))
d <- d + geom_line()
# d <- d + facet_grid(dummy1 ~ dummy2)
d <- d + geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.25)
d
# using facets
e <- ggplot(c, aes(scale, fit))
e <- e + geom_line()
e <- e + facet_grid(dummy1 ~ dummy2)
e <- e + geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.25)
e
我应该包括这些情节。