[R] How to plot effect of x1 while controlling for x2
Mark Na
mtb954 at gmail.com
Mon Nov 15 22:40:11 CET 2010
Hello R-helpers,
Please see a self-contained example below, in which I attempt to plot
the effect of x1 on y, while controlling for x2.
Is there a function that does the same thing, without having to
specify that x2 should be held at its mean value? It works fine for
this simple example, but might be cumbersome if the model was more
complex (e.g., lots of x variables, and/or interactions).
Many thanks,
Mark
#make some random data
x1<-rnorm(100)
x2<-rnorm(100,2,1)
y<-0.75*x1+0.35*x2
#fit a model
model1<-lm(y~x1+x2)
#predict the effect of x1 on y, while controlling for x2
xv1<-seq(min(x1),max(x1),0.1)
yhat_x1<-predict(model1,list(x1=xv1,x2=rep(mean(x2),length(xv1))),type="response")
#plot the predicted values
plot(y~x1,xlim=c(min(x1),max(x1)), ylim=c(min(y),max(y)))
lines(xv1,yhat_x1)
More information about the R-help
mailing list