1
$\begingroup$

I'm trying to make my results more intuitive, and so I want to compare the predicted values at the interquartile range. I'm trying to figure out how to get the predicted value for a given variable, keeping everything else at the median.

I've tried something like this:

x_1 <- rnorm(20)
x_2 <- rnorm(20)
y <- x_1 + x_2 + rnorm(20)
z <- data.frame(y,x_1,x_2)
fit <- lm(y~x_1 + x_2,data = z)
predict(fit,newdata = data.frame(x_1=c(quantile(x_1)[2],quantile(x_1)[4]), x_2=median(x_2)))

which works, but my actual model has 10+ variables, and this starts to get ugly really quickly, so I figure there must be a better way?

$\endgroup$

1 Answer 1

1
$\begingroup$

I think the apply() function is what you need here.

Try

data <- matrix(rnorm(20*10), ncol = 10, nrow = 20)
y <- apply(data, 1, sum) + rnorm(20)
z <- data.frame(y,data)
fit <- lm(y~ . ,data = z)

i <- 1  ### Predictions for variable i
meds  <- apply(data[,-i], 2, median)
new <- cbind(c(quantile(data[,i])[2],quantile(data[,i])[4]), matrix(meds, nrow = 2, ncol = length(meds), byrow = T))
predict(fit, newdata = data.frame(new))
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.