Skip to content
Prev 241680 / 398500 Next

How to plot effect of x1 while controlling for x2

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
example:


## original data
set.seed(1355)
dat <- data.frame(matrix(rnorm(100), ncol = 10, dimnames = list(NULL,
letters[1:10])))
## 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)

Cheers,

Josh
On Mon, Nov 15, 2010 at 1:40 PM, Mark Na <mtb954 at gmail.com> wrote: