2013-04-21 83 views
1

我對R完全陌生,想將我的數據集中的每個列標籤(標題?)轉換爲迴歸因子,而不必每次定義一個迴歸因子,即日期 - > data $日期將所有列標題轉換爲R中的迴歸因子

有沒有辦法一次完成這一切?

預先感謝您!

+2

你可以發佈一個簡單的可重複的例子嗎?你到現在爲止嘗試過什麼? – Nishanth 2013-04-21 05:00:07

回答

4

這是你想要的東西:

R > data(iris) 
R > head(iris) 
    Sepal.Length Sepal.Width Petal.Length Petal.Width Species 
1   5.1   3.5   1.4   0.2 setosa 
2   4.9   3.0   1.4   0.2 setosa 
3   4.7   3.2   1.3   0.2 setosa 
4   4.6   3.1   1.5   0.2 setosa 
5   5.0   3.6   1.4   0.2 setosa 
6   5.4   3.9   1.7   0.4 setosa 
R > lm(Sepal.Length ~ ., data = iris) 

Call: 
lm(formula = Sepal.Length ~ ., data = iris) 

Coefficients: 
     (Intercept)  Sepal.Width  Petal.Length  Petal.Width 
      2.1713    0.4959    0.8292   -0.3152 
Speciesversicolor Speciesvirginica 
      -0.7236   -1.0235 
+0

太棒了!謝謝! – user2303635 2013-04-21 07:00:51

1

如果你要選擇你可以使用這個特定的列:

數據sample.data與因變量在col 3cols 1, 2, 4:8是獨立變量

yy<-lm(as.formula(paste(colnames(sample.data)[3], "~",paste(colnames(sample.data)[c(1, 2,4:8)], collapse = "+"), sep = "")), data=sample.data) 
    ) 
summary(yy)