Robert Kubrick
Robert Kubrick

Reputation: 8713

Extracting dependent variable from lm object

Is there a function to extract Y from an lm object?

I use residual(m) and predict(m) but am using the object internal structures to extract Y...

m = lm(Y ~ X1, d)
head(m$model$Y)
[1] -0.791214 -1.291986 -0.472839  1.940940 -0.977910 -1.705539

Upvotes: 5

Views: 4299

Answers (1)

alexforrence
alexforrence

Reputation: 2744

You could use model.frame(), like the following:

# From the stats::lm documentation
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("Ctl","Trt"))
weight <- c(ctl, trt)
lm1 <- lm(weight ~ group)

model.frame(lm1)$weight
##  [1] 4.17 5.58 5.18 6.11 4.50 4.61 5.17 4.53 5.33 5.14 4.81 4.17 4.41 
##  3.59 5.87 3.83 6.03 4.89 4.32 4.69

If you call a function on one or more of the variables in your formula, like

lm2 <- lm(log(weight) ~ group)

You can get the untransformed values with get_all_vars(lm2)$weight (model.frame() returns the transformed values).

If you want to see what functions (particularly extractor functions) are available for a particular class, you can check using methods(class = "lm") (or whatever object class you're interested in).

Upvotes: 4

Related Questions