2

I have a more complicated function that I am working on. I want to pass a variable around inside of my function to do several things. The part that is not working is trying to access an object that has my variable's name embedded in it.

A simple example would be as follows:

    ## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
    ## Page 9: Plant Weight Data.

    ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
    trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
    group <- gl(2,10,20, labels=c("Ctl","Trt"))
    weight <- c(ctl, trt)

    D9.fit.lm <- lm(weight ~ group)

    my.coeff <- function(mname)
       {
        b  <-  round(mname.fit.lm$coef[1],2)
        m  <-  round(mname.fit.lm$coef[2],4)
        r2 <-  round(summary(mname.fit.lm)$r.squared,2)

        cbind(b, m, r2)
       }

So if I try this bit of code like this:

 my.coeff("D9")

Then I get the following error:

 Error in my.coeff("D9") : object 'mname.fit.lm' not found

I really my function to work and it should look like this output

 cbind(round(D9.fit.lm$coef[1],2),round(D9.fit.lm$coef[2],4),round(summary(D9.fit.lm)$r.squared,2))
             [,1]   [,2] [,3]
 (Intercept) 5.03 -0.371 0.07

Thanks !

3 Answers 3

4

Just add this line inside you function

mname.fit.lm <- get(paste(mname, ".fit.lm", sep = ""))
Sign up to request clarification or add additional context in comments.

1 Comment

Aside from missing a parenthesis this does it ! mname.fit.lm <- get(paste(mname, ".fit.lm", sep = "")) Thanks !!
1

you're passing a character string into your function. It looks like you should possibly be passing a lm object.

so something like this:

my.coeff <- function(mname)
{
  b  <-  round(mname$coef[1],2)
  m  <-  round(mname$coef[2],4)
  r2 <-  round(summary(mname)$r.squared,2)

  cbind(b, m, r2)
}

my.coeff(D9.fit.lm)

1 Comment

I believe this is the approach recommended in the R Inferno.
1

As Ramnath says, sometimes people solve this problem with get. But I agree with JD that in this case you should just choose a better way of storing your lm objects. Another option is to store them in a named list:

fit.lm <- list()
fit.lm[["D9"]] <- lm(weight ~ group)

my.coeff <- function(mname)
{
    b  <-  round(fit.lm[[mname]]$coef[1],2)
    m  <-  round(fit.lm[[mname]]$coef[2],4)
    r2 <-  round(summary(fit.lm[[mname]])$r.squared,2)

    cbind(b, m, r2)
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.