Fórmulas en las funciones definidas por el usuario en R
Pregunta
Fórmulas son una característica muy útil de funciones estadísticas y gráficos de R. Como todos, yo soy un usuario de estas funciones. Sin embargo, nunca he escrito una función que toma un objeto fórmula como argumento. Me preguntaba si alguien me podría ayudar, ya sea por ligarse a una introducción legible a este lado de la programación R, o dando un ejemplo autónomo.
Solución
Puede utilizar model.matrix()
y model.frame()
para evaluar la fórmula:
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))
que produce
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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow