[R] How to plot effect of x1 while controlling for x2

Joshua Wiley jwiley.psych at gmail.com
Mon Nov 15 23:14:03 CET 2010

Hi Mark,

If the cumbersome part is that you have to create new data to use
predict, then I think the answer is "no", there is not an easier way.
However, we can consider easy ways to make new data that fit with
certain constraints (e.g., variables = their mean).  Here's an

## original data
dat <- data.frame(matrix(rnorm(100), ncol = 10, dimnames = list(NULL,
## model predicting column a from all others
model <- lm(a ~ ., data = dat)

## lets say "b" is the column of interest
bnew <- seq(0, 2, .1)
## create dataframe of means
newdat <- data.frame(t(mean(dat, na.rm = TRUE)))
## repeat the rows so it is as long as bnew
newdat <- newdat[rep(1, length(bnew)), ]
newdat$b <- bnew
## make predictions using your new data
predict(model, newdat)

Let's say you had a huge original data frame and you only used some of
the variables, you could extract just the terms you included in your
model.  This should give you the column names, which you could use to
calculate the mean on a limited number of variables.

attr(terms(model), "term.labels")

Finally, if you have taken the (not uncommon and sometimes quite
beneficial) step of mean centering your variables prior to creating
your model, your task is even simpler:

cbind(1:10, 0)



On Mon, Nov 15, 2010 at 1:40 PM, Mark Na <mtb954 at gmail.com> wrote:
> 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)
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles

More information about the R-help mailing list