简体   繁体   English

如何从 R 中的 lm 打印出设计矩阵?

[英]How can I print out the design matrix from lm in R?

Assume x2-x4 are continuous predictors occupying one column each in the design matrix created using lm() in R. I want to include x1 a categorical variable that has 3 levels.假设 x2-x4 是连续预测变量,在 R 中使用 lm() 创建的设计矩阵中各占据一列。我想包括 x1 一个具有 3 个级别的分类变量。

Regression R code:回归R代码:
fit <- lm(y~as.factor(x1)+x2+x3+c4,data=mydata)适合 <- lm(y~as.factor(x1)+x2+x3+c4,data=mydata)

How can I print the design matrix from lm() in R and what would it look like?如何从 R 中的 lm() 打印设计矩阵,它会是什么样子? I need to know the default coding used in R so I can write contrast statements properly.我需要知道 R 中使用的默认编码,以便我可以正确编写对比语句。

I think the model.matrix() function is what you're after.我认为model.matrix()函数就是你所追求的。

As kjetil b halvorsen says you can specify the model in the argument.正如kjetil b halvorsen所说,您可以在参数中指定模型。 Or you can just hand model.matrix the defined model.或者你可以只手model.matrix定义的模型。

fit <- lm(y~as.factor(x1)+x2+x3+c4,data=mydata)
model.matrix(fit)

You can even get a design matrix for new data: model.matrix(fit, data=newdata)您甚至可以获得新数据的设计矩阵: model.matrix(fit, data=newdata)

The comment by kjetil b halvorsen helped me the most: kjetil b halvorsen评论对我帮助最大:

call res <- lm() with the argument x=TRUE then the design matrix will be returned in the model object res Then call str(res) to see the structure of res , and you will now how to get the design matrix from it.使用参数x=TRUE调用res <- lm()然后将在模型对象res返回设计矩阵然后调用str(res)以查看res的结构,您现在将了解如何从中获取设计矩阵. But easier is to call model.matrix(y ~ x + f, data=...) with the same model formula you use in lm .但更简单的是使用您在lm使用的相同模型公式调用model.matrix(y ~ x + f, data=...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM