Gene
Gene

Reputation: 31

Error in eval(expr, envir, enclos) : object 'c2' not found [The irony is that this column exists in the dataframe]

I am trying to write a function. The data consists of ten columns.

alpha
c1 c2  c3 c4....c10
1  0.4  a
2  0.3  b 
1  -1.2  c

I want to apply regression for five such columns. So, I tried to write a function.

function.one <- function(c) {
    glm(c1~c2,data=alpha) }

 function(c=c2)

I get the error such as

Error in eval(expr, envir, enclos) : object 'c2' not found

Could someone tell me why I get this error eventhough c2 is in the dataset.

Upvotes: 0

Views: 113

Answers (1)

Taylor H
Taylor H

Reputation: 436

The problem is that c2 is in your dataset, not the global environment. When you wrote f(c2), R looks for c2 defined in the global environment, and cannot find it. R does not know to dig around in the column names of your data.frame.

Supposing your data is a data.frame, you would need to reference it as df$c2 or df[["c2"]] or df[,"c2"].

You should probably read up on standard vs. non-standard evaluation in R, as it applies to writing such a function as you desire.

Upvotes: 1

Related Questions