且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

新手需要在R中循环lm

更新时间:2022-11-15 11:34:28

我个人认为问题不那么容易.特别适合R新手.

Personally I don't find the problem so easy. Specially for an R novice.

这里有一个基于动态创建回归公式的解决方案. 想法是使用paste函数创建不同的公式项,然后使用as.formula强制使用y~ x + var + x * var强制结果字符串tp一个公式.此处yx是公式动态项:c(trait1,trai2,..)中的y和c(SNP1,SNP2,...)中的x.当然,这里我使用lapply进行循环.

Here a solution based on creating dynamically the regression formula. The idea is to use paste function to create different formula terms, y~ x + var + x * var then coercing the result string tp a formula using as.formula. Here y and x are the formula dynamic terms: y in c(trait1,trai2,..) and x in c(SNP1,SNP2,...). Of course here I use lapply to loop.

lapply(1:3,function(i){
 y <- paste0('trait',i)
 x <- paste0('SNP',i)
 factor1 <- x
 factor2 <- 'var'
 factor3 <- paste(x,'var',sep='*')
 listfactor <- c(factor1,factor2,factor3)
 form <- as.formula(paste(y, "~",paste(listfactor,collapse="+")))
 lm(formula = form, data = dat)
})

我希望有人能提供更简单的解决方案,或者更多的R-ish解决方案:)

I hope someone come with easier solution, ore more R-ish one:)

编辑

由于@DWin注释,我们可以将公式简化为y~x*var,因为这意味着yxvarx*var

Thanks to @DWin comment , we can simplify the formula to just y~x*var since it means y is modeled by x,var and x*var

因此,上面的代码将简化为:

So the code above will be simplified to :

 lapply(1:3,function(i){
     y <- paste0('trait',i)
     x <- paste0('SNP',i)
     LHS <- paste(x,'var',sep='*')
     form <- as.formula(paste(y, "~",LHS)
     lm(formula = form, data = dat)
    })