Reputation: 697
I am trying to use step function for AIC-based model selection in a tidyverse workflow. However, I receive an error:
Error in is.data.frame(data) : object '.' not found.
I need the tidyverse workflow for occasional filtering of the data. What should I do?
mean_mpg <- mean(mtcars$mpg)
# creating a new variable that shows that Miles/(US) gallon is greater than the mean or not
mtcars <-
mtcars %>%
mutate(mpg_cat = ifelse(mpg > mean_mpg, 1,0))
mtcars$cyl <- as.factor(mtcars$cyl)
mtcars_lr <-
mtcars %>%
select (cyl,vs, am, mpg_cat) %>%
glm(formula = mpg_cat ~ cyl+vs+ am,
data =., family = "binomial")
step(mtcars_lr)
Upvotes: 1
Views: 453
Reputation: 11981
this has to do with the magrittr
pipe %>%
. In this technical note you can find the following paragraph:
The magrittr pipe operators use non-standard evaluation. They capture their inputs and examines them to figure out how to proceed. First a function is produced from all of the individual right-hand side expressions, and then the result is obtained by applying this function to the left-hand side. For most purposes, one can disregard the subtle aspects of magrittr's evaluation, but some functions may capture their calling environment, and thus using the operators will not be exactly equivalent to the "standard call" without pipe-operators.
This means that very often x %>% f
is equivalent to f(x)
. In your case it is not.
You will have to do something like this:
mtcars2 <- mtcars %>%
mutate(mpg_cat = if_else(mpg > mean_mpg, 1,0),
cyl = as.factor(cyl)) %>%
select (cyl, vs, am, mpg_cat)
glm(formula = mpg_cat ~ cyl + vs + am,
data = mtcars2, family = "binomial") %>%
step(mtcars_lr)
To see the difference you can try the following:
x1 <- glm(formula = mpg_cat ~ cyl + vs + am,
data = mtcars2, family = "binomial")
x2 <- mtcars2 %>% glm(formula = mpg_cat ~ cyl + vs + am,
data = ., family = "binomial")
all.equal(x1, x2)
[1] "Component “call”: target, current do not match when deparsed"
So the call components of x1
and x2
are different and the step
function uses this argument.
Upvotes: 1