R笔记(1):formula和Formula

#####开一个新的系列。关于R的一些笔记,就是遇到过的一些问题的简单整理。可能很基本,也可能没什么大的用处,作为一个记录而已。
---------------------------------------------------------------------------
R笔记(1):formula和Formula

1.基本的R公式对象formula

在R当中,公式fomula是一个把响应变量(在~左侧)和解释变量(在~右侧)联系起来的对象。formula可以用在线性/一般线性模型(如lm(),glm()),树方法(如rpart())和图形表示(如coplot())以及其它一些场合(如table())。formula在这些场合中给出了关于统计模型的简洁而统一的符号模型形式y ~ model。

关于formula这种处理方法的思想可能最早来自于方差分析。在 Chambers and Hastie (1993) “Statistical Models in S” 这本书当中给出了S语言(以及后来的R语言)formula的明确参考。他们把统计模型的形式分为三个部分,其中“a formula that defines the structural part of the model-that is, what data are being modeled and by what other data, in what form”。

(1)formula的例:

fit2 <- lm(weight ~ height + I(height^2), data = women)

(2)关于formula所常用的符号,参见下表(取自R in action ):

 




(3)创建包含很多个解释变量的公式的一种方法是使用paste():

xnam <- paste0("x", c(1:10, 15, 20:25))
(f <- as.formula(paste("y ~ ", paste(xnam, collapse = "+"))))
## y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x15 + 
## x20 + x21 + x22 + x23 + x24 + x25
# 或者
xnam <- paste("x", c(1:10, 15, 20:25), sep = "")
(f <- as.formula(paste("y ~ ", paste(xnam, collapse = "+"))))
## y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x15 + 
## x20 + x21 + x22 + x23 + x24 + x25
formula对象的细节参考:?formula

2.Fomula包

Formula包提供了关于R中模型公式的一个扩展,可以在~右侧(RHS)和(或)左侧(LHS)加入多个部分,相应的模型对象叫做Fomula。

这个包的目的是解决formula对象的一些局限:不支持多个响应变量也不方便处理由几个不同部分处理的公式。在一些R的扩展包当中用各自的方法处理这些问题,Forluma包希望给出一种统一的方法。

在形式上,Formula对象对于formula对象的扩展在于:引入新的运算符|以容纳模型的多个部分,并可将formula的运算符应用于LHS。

一个简单的例子:

library(Formula)
f1 <- y1 | y2 + y3 ~ x1 + I(x2^2) | 0 + log(x1) | x3/x4
F1 <- Formula(f1)
length(F1)
## [1] 2 3
length()的结果说明这个Fomula的左侧有两个部分,右侧有三个部分。

关于这个包的细节可参考: Zeileis A, Croissant Y (2010). “Extended Model Formulas in R: Multiple Parts and Multiple Responses.” Journal of Statistical Software, 34(1), 1–13.http://www.jstatsoft.org/v34/i01/.

转自:数据铺子

---------------------------------------------------------------------------------- 数据和特征决定了效果上限,模型和算法决定了逼近这个上限的程度 ----------------------------------------------------------------------------------
原文地址:https://www.cnblogs.com/payton/p/5412356.html