R中具有变量不同组合的线性模型 [英] Linear models in R with different combinations of variables

查看:95
本文介绍了R中具有变量不同组合的线性模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的新手,并且遇到了问题.我正在尝试读取表中的一组数据,并且想要执行线性建模.以下是我如何读取数据和变量名称的方法:

I am new to R and I am stuck with a problem. I am trying to read a set of data in a table and I want to perform linear modeling. Below is how I read my data and my variables names:

>data =read.table(datafilename,header=TRUE)
>names(data)
[1] "price"     "model"     "size"   "year"   "color"

我想做的是使用变量的不同组合(价格为目标)创建多个线性模型,例如:

What I want to do is create several linear models using different combinations of the variables (price being the target ), such as:

> attach(data)
> model1 = lm(price~model+size)
> model2 = lm(price~model+year)
> model3 = lm(price~model+color)
> model4 = lm(price~model+size)
> model4 = lm(price~size+year+color)
#... and so on for all different combination...

我的主要目的是比较不同的模型.有没有一种更聪明的方法来生成这些模型,而不是对变量进行硬编码,尤其是在某些情况下,我的变量数将增加到13个左右.

My main aim is to compare the different models. Is there a more clever way to generate these models instead of hard coding the variables, especially that the number of my variables in some cases will increase to 13 or so.

推荐答案

这是使用combn函数获取所有变量组合的一种方法.有点混乱,并使用了一个循环(也许有人可以使用mapply对此进行改进):

Here's one way to get all of the combinations of variables using the combn function. It's a bit messy, and uses a loop (perhaps someone can improve on this with mapply):

vars <- c("price","model","size","year","color")
N <- list(1,2,3,4)
COMB <- sapply(N, function(m) combn(x=vars[2:5], m))
COMB2 <- list()
k=0
for(i in seq(COMB)){
    tmp <- COMB[[i]]
    for(j in seq(ncol(tmp))){
        k <- k + 1
        COMB2[[k]] <- formula(paste("price", "~", paste(tmp[,j], collapse=" + ")))
    }
}

然后,您可以调用这些公式并使用list存储模型对象,或者可以使用assign函数给出唯一的名称:

Then, you can call these formulas and store the model objects using a list or possibly give unique names with the assign function:

res <- vector(mode="list", length(COMB2))
for(i in seq(COMB2)){
    res[[i]] <- lm(COMB2[[i]], data=data)
}

这篇关于R中具有变量不同组合的线性模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆