2009-08-19 46 views
10

公式是R的統計和圖形函數的一個非常有用的功能。像所有人一樣,我是這些功能的使用者。但是,我從來沒有寫過一個將公式對象作爲參數的函數。我想知道是否有人可以幫助我,或者鏈接到R編程的可讀介紹,或者提供一個獨立的示例。R中的用戶自定義函數中的公式

回答

6

您可以使用model.matrix()model.frame()評估公式:

lm1 <- lm(log(Volume) ~ log(Girth) + log(Height), data=trees) 
print(lm1) 

form <- log(Volume) ~ log(Girth) + log(Height) 

# use model.matrix 
mm <- model.matrix(form, trees) 
lm2 <- lm.fit(as.matrix(mm), log(trees[,"Volume"])) 
print(coefficients(lm2)) 

# use model.frame, need to add intercept by hand 
mf <- model.frame(form, trees) 
lm3 <- lm.fit(as.matrix(data.frame("Intercept"=1, mf[,-1])), mf[,1]) 
print(coefficients(lm3)) 

這將產生

Call: lm(formula = log(Volume) ~ log(Girth) + log(Height), data = trees) 

Coefficients: (Intercept) log(Girth) log(Height) 
     -6.63   1.98   1.12 

(Intercept) log(Girth) log(Height) 
    -6.632  1.983  1.117 
Intercept log.Girth. log.Height. 
    -6.632  1.983  1.117 
+1

謝謝,非常有趣。我也明白爲什麼glmnet或ther包可能不提供這種功能:它在包Matrix中使用稀疏矩陣,這可能不會被model.matrix()處理。 – gappy 2009-08-19 18:24:20