I just wrote this function for personal use only while working on a specific data project. I would be grateful for any feedback!
get.coef1 <- function(x) {
x <- as.character(x)
m.names <- paste("fit", x, letters[1:3], sep="")
models3 <- matrix(numeric(12L), 3, 4)
for (i in 1:3) {
models3[i, ] <- summary(get(m.names[i]))$coefficients[2,]
}
return(models3)
}
Data to reproduce function above:
x <- rnorm(100)
y <- x^2/4
z <- rnorm(100)+y/100
w <- rnorm(100)
Edit1: And three fitted regressions:
fit3a <- lm(y ~ x)
fit3b <- lm(y ~ x + z)
fit3c <- lm(y ~ x + z + w)
Whose coefficients on x
I want to access viaget.coef1(3)
.
1 Answer 1
Your function has several problematic assumptions for the object names in the environment (get()
) and the number of objects (fixed length in the for
loop).
In base R it would be more idiomatic and flexible to use some function from the *apply family, which operate on a list of objects, e.g.
do.call(rbind, lapply(list(fit3a, fit3b, fit3c),
function(x) summary(x)$coefficients["x", ]))
Estimate Std. Error t value Pr(>|t|)
[1,] 0.01512 0.02927 0.5164 0.6067
[2,] 0.01530 0.02985 0.5127 0.6093
[3,] 0.01732 0.02899 0.5975 0.5516
t(sapply(list(fit3a, fit3b, fit3c),
function(x) summary(x)$coefficients["x", ]))
Estimate Std. Error t value Pr(>|t|)
[1,] 0.01512 0.02927 0.5164 0.6067
[2,] 0.01530 0.02985 0.5127 0.6093
[3,] 0.01732 0.02899 0.5975 0.5516
Output of get.coef1(3)
(with set.seed(1)
):
[,1] [,2] [,3] [,4]
[1,] 0.01512 0.02927 0.5164 0.6067
[2,] 0.01530 0.02985 0.5127 0.6093
[3,] 0.01732 0.02899 0.5975 0.5516
fit{something}{a,b,c}
objects in your environment? Can you show how these were built? Thank you. \$\endgroup\$