简体   繁体   English

创建具有因子的矩阵lm模型

[英]create matrix lm model with factors

I'd like to create 100 simulations and create a linear model for each model using a matrix. 我想创建100个仿真,并使用矩阵为每个模型创建一个线性模型。 I used the following code, but got an error. 我使用以下代码,但出现错误。 What is the best way to accomplish this? 做到这一点的最佳方法是什么?

n=15;nsims=100
factor=matrix(as.factor(rep(1:5,3)),n, nsims)
sim=matrix(rnorm(nfactor*nsims,0,1),n,nsims)
> dim(factor)
[1]  15 100
> lm1=lm(sim~factor)
Error in `[[<-.data.frame`(`*tmp*`, i, value = c(1L, 2L, 3L, 4L, 5L, 1L,  : 
  replacement has 1500 rows, data has 15

I'm not clear what you want. 我不清楚你想要什么。

Create data: 创建数据:

n <- 15; nsims <- 100; nfactor <- 5
f <- matrix(as.factor(rep(1:nfactor,n/nfactor)), n, nsims)
set.seed(101)
sim <- matrix(rnorm(nfactor*nsims,0,1),n,nsims)

(In general it's bad practice to name variables with the names of existing functions ( factor ) ...) (通常,用现有函数的名称( factor )来命名变量是不明智的做法。)

res <- vector("list", nsims)
for (i in 1:nsims) {
   res[[i]] <- lm(y~x,
                  data=data.frame(y=sim[,i],x=f[,i]))
}

A for loop may seem clunky, but (as discussed in chapter 4 of the R Inferno ) it's often the clearest way to write your code ... If you really want to do it without a for loop, inu the general case where the columns of f might differ, you could do for循环可能看起来很笨拙,但是(如R Inferno的第4章所讨论),它通常是编写代码的最清晰的方法...如果您确实想在没有for循环的情况下进行编码,那么请输入一般情况下的列的f可能有所不同,您可以

res2 <- mapply(function(x,y) lm(y~x),
            split(f,col(f)),split(sim,col(sim)),SIMPLIFY=FALSE)

but I consider that less clear than the for loop ... 但是我认为这比for循环还不清楚...

update : I don't know whether it was on purpose or not, but every column of your factor matrix is identical. 更新 :我不知道它是否是故意的,但是因子矩阵的每一列都是相同的。 Thus you can put the single input variable on the right-hand side of the formula and the matrix response on the left-hand side: 因此,您可以将单个输入变量放在公式的右侧,将矩阵响应放在左侧:

all(apply(f[,-1],2,identical,f[,1]))  ## all TRUE
res2 <- lm(sim~f[,1])

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

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