4
\$\begingroup\$

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).

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to Code Review! I hope you get some great answers. \$\endgroup\$
    – Phrancis
    Aug 9, 2016 at 23:44
  • 1
    \$\begingroup\$ Welcome. Could you show us what input you use when making a call to the function? Also, does the function not assume you have fit{something}{a,b,c} objects in your environment? Can you show how these were built? Thank you. \$\endgroup\$
    – flodel
    Aug 10, 2016 at 1:12
  • \$\begingroup\$ The function assumes I have fit 3 regressions. I just added an example. \$\endgroup\$
    – snoram
    Aug 10, 2016 at 1:32

1 Answer 1

3
\$\begingroup\$

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
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.