i having lot of trouble figuring out how find predicted values coefficients of models , model matrix. i'm hoping can help.
i have linear model 2 independent variables setting up. e.g.
data <- data.frame(d1,d2,d3) lm.data <- lm(d1~d2*d3,data) i can coefficient vector
co.data <- coef(lm.data) i can model matrix
mm.data <- model.matrix(lm.data) this can lost!! trying teach myself how can match values can when use predict(lm.data) coefficients. in other words, know predicted values of model design matrix , coefficients can calculated, after past 48 hours of working on this, have no idea.
any amazing.
you need know how linear model works. if formula d1 ~ d2 * d3 , they're numeric, predict (intercept) + (d2 coefficient)*x_d2 + (d3 coefficient)*x_d3 + (d2:d3 coefficient)*x_d2*x_d3 , give predicted d1.
here's reproducible example:
data(iris) m <- lm(sepal.length ~ petal.length * sepal.width, iris) co.data <- coef(m) # we'll predict sepal length these petal lengths , sepal widths: x.pl <- runif(5, min=1, max=2) x.sw <- runif(5, min=2, max=5) y.predicted <- predict(m, data.frame(petal.length=x.pl, sepal.width=x.sw)) # 1 2 3 4 5 # 5.379006 5.495907 5.296913 4.382487 5.131850 now manually, let's @ coefficients:
co.data # intercept) petal.length sepal.width petal.length:sepal.width # 1.40438275 0.71845958 0.84995691 -0.07701327 according formula above:
y <- co.data[1] + co.data[2]*x.pl + co.data[3] * x.sw + co.data[4]*x.pl*x.sw # [1] 5.379006 5.495907 5.296913 4.382487 5.131850 rather writing out manually can like:
# x matrix columns 1, petal length, sepal width, pl*sw # (matches order of co.data) x <- cbind(1, matrix(c(x.pl, x.sw, x.pl*x.sw), ncol=3)) x %*% co.data # [,1] # [1,] 5.379006 # [2,] 5.495907 # [3,] 5.296913 # [4,] 4.382487 # [5,] 5.131850
Comments
Post a Comment