Reputation: 176
I'm really struggling to understand why this function is not working. It's just a function to return the coefficients of a simple linear model:
lmfunction <- function(data,y,x,index){
return(coef(lm(y~x,data=data,subset=index)))
}
Now I create any random dataset:
dataset <- data.frame(x=rnorm(100),y=rnorm(100)*2)
When I try to run the function on dataset I get the following error:
lmfunction(dataset,y,x,1:100)
Error in eval(predvars, data, env) : object 'y' not found
The y variable definitely exists so I'm not understanding this error.
EDIT:
I restarted my r session and the above code worked. However, if I use it on a real dataset I still run in to problems:
data(iris)
lmfunction(iris,Sepal.Length,Petal.Length,1:150)
Error in eval(predvars, data, env) : object 'Sepal.Length' not found
Upvotes: 1
Views: 14024
Reputation: 8110
If you want the structure of your function to remain as 4 inputs with no quotes, we can do as follows:
library(dplyr)
lmfunction <- function(data, y, x, index){
data %>%
select(my_y = !!enquo(y), my_x = !!enquo(x)) %>%
lm(my_y~my_x, data = ., subset = index) %>%
coefficients()
}
lmfunction(iris, Sepal.Length, Petal.Length, 1:150)
#> (Intercept) my_x
#> 4.3066034 0.4089223
lmfunction(mtcars, qsec ,mpg, 1:32)
#> (Intercept) my_x
#> 15.3547689 0.1241366
What we do is wrap the variables you want in enquo
in order to avoid the "object '**' not found" error. Then we simultaneously select the variables and rename them. The reason I renamed was that I found it hard to feed a quosure into lm
. Then we run the lm
using our newly named variables.
Upvotes: 0
Reputation: 2261
Unlike most other functions you probably built you are not passing objects: you are trying to build a formula, hence the error.
lmFunc <- function(data, formula){
formula <- as.formula(formula)
lm <- lm(formula, data)
coef(lm)
}
lmFunc(mtcars, qsec ~ mpg)
Upvotes: 3