2017-05-13 1 views
0

ggplot을 사용하여 "효과"패키지로 얻은 부분 부분 효과 (부분 잔류 포함)를 복제하고 싶습니다. 이렇게하려면 몇 가지 정보를 검색해야합니다. 이것은 ggplot으로 복제하고자하는 플롯입니다. 내가 eff$residuals로, 부분 잔차를 검색 할 수 오전 eff 객체에서 ggplot을 사용하여 효과 라이브러리로 얻은 부분 효과를 그립니다.

Partial effect plot of Education Term

library(effects)  
mod <- lm(log(prestige) ~ income:type + education, data=Prestige) 
eff = effect("education", mod, partial.residuals=T) 

plot(eff) 

,하지만 그들은 음모를 복제하기에 충분하지 않다. 나는 내가 필요로하는 것은 잔차와 한계 예측 효과 모두라고 생각한다. 그러나 내 eff 개체에서 검색 할 수 없습니다. 그렇지 않으면 한계 효과의 선에 대해 플롯 할 수없는 잔차 점수 만 있습니다.

이 정보를 검색하는 방법에 대한 힌트가 있습니까?

답변

1

사용할 수있는 거의 모든 정보가 있습니다. 이것은 일반화하는데 좀 더 시간이 걸릴 것이지만, 대략 effects 패키지와 같은 형태의 코드가 있습니다. 매끄러운 것은 꺼져 있지만, 나는 그 이유를 파헤 치지 않았다.

코드는 설명이 있어야합니다. 나는 the package에서 함수 closest 만 복사했습니다.

mod <- lm(log(prestige) ~ income:type + education, data=Prestige) 
eff = effect("education", mod, partial.residuals=T) 

library(ggplot2) 
library(gridExtra) 

closest <- function(x, x0) apply(outer(x, x0, FUN=function(x, x0) abs(x - x0)), 1, which.min) 

x.fit <- unlist(eff$x.all) 
trans <- I 
x <- data.frame(lower = eff$lower, upper = eff$upper, fit = eff$fit, education = eff$x$education) 
xy <- data.frame(x = x.fit, y = x$fit[closest(trans(x.fit), x$education)] + eff$residuals) 

g <- ggplot(x, aes(x = education, y = fit)) + 
    theme_bw() + 
    geom_line(size = 1) + 
    geom_point(data = xy, aes(x = x, y = y), shape = 1, col = "blue", size = 2) + 
    geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.5) + 
    geom_smooth(data = xy, aes(x = trans(x), y = y), 
       method = "loess", span = 2/3, linetype = "dashed", se = FALSE) 

grid.arrange(plot(eff), g, ncol = 2) 

enter image description here

관련 문제