5

式の右辺に入る変数の数を数えたいと思います。これを行う機能はありますか?

例えば:

y<-rnorm(100)
x1<-rnorm(100)
x2<-rnorm(100)
x3<-rnorm(100)
f<-formula(y~x1+x2+x3)

次に、これを呼び出しSomeFunction(f)て 3 を返します (式の右側に 3 つの x 変数があるため)。SomeFunction は存在しますか?

4

4 に答える 4

8

のヘルプ ページにリンクされている関連機能の一部を参照する必要がある場合がありますformula。特に、terms:

> terms(f)
y ~ x1 + x2 + x3 + x4
attr(,"variables")
list(y, x1, x2, x3, x4)
attr(,"factors")
   x1 x2 x3 x4
y   0  0  0  0
x1  1  0  0  0
x2  0  1  0  0
x3  0  0  1  0
x4  0  0  0  1
attr(,"term.labels")
[1] "x1" "x2" "x3" "x4"
attr(,"order")
[1] 1 1 1 1
attr(,"intercept")
[1] 1
attr(,"response")
[1] 1
attr(,".Environment")
<environment: R_GlobalEnv>

「term.labels」属性に注意してください。

于 2013-08-16T19:11:30.063 に答える
7

次の 2 つの可能性があります。

length(attr(terms(f), "term.labels"))

length(all.vars(update(f, z ~.))) - 1
于 2013-08-16T19:13:13.710 に答える
1

G. Grothendieck の回答の下にあるコメントで示唆されているように、推定されたパラメーターの数を数えたい場合は、以下のコードを試すことができます。n.coefficientsAIC で行われているように、誤差項に1 つ追加しました。

n      <- 20                                       # number of observations
B0     <-  2                                       # intercept
B1     <- -1.5                                     # slope 1
B2     <-  0.5                                     # slope 2
B3     <- -2.5                                     # slope 3
sigma2 <-  5                                       # residual variance

x1     <- sample(1:3, n, replace=TRUE)             # categorical covariate
x12    <- ifelse(x1==2, 1, 0)
x13    <- ifelse(x1==3, 1, 0)
x3     <- round(runif(n, -5 , 5), digits = 3)      # continuous covariate
eps    <- rnorm(n, mean = 0, sd = sqrt(sigma2))    # error
y      <- B0 + B1*x12 + B2*x13 + B3*x3 + eps       # dependent variable
x1     <- as.factor(x1)

model1 <- lm(y ~ x1 + x3)                          # linear regression
model1

summary(model1)

n.coefficients <- as.numeric(sapply(model1, length)[1]) + 1
n.coefficients

# [1] 5

のコードのより簡単な代替方法を次に示しますn.coefficients

# For each variable in a linear regression model, one coefficient exists
# An intercept coefficient exists as well
# Subtract -1 to account for the intercept
n.coefficients2 <- length(model1$coefficients) - 1
n.coefficients2

# [1] 5
于 2013-08-17T01:25:38.910 に答える