Reputation: 13319
I'm trying to map the function below to a nested dataframe using purrr. I've tried to look at the docs but just can't wrap my head around a way to pass additional arguments to the function.
Sample data:
library(dplyr)
library(purrr)
nested<-iris %>%
group_by(Species) %>%
nest()
Function to implement:
lm_mod<-function(df,xname,yname){
xname<-deparse(substitute(xname))
yname<-deparse(substitute(yname))
f1<-as.formula(paste(yname,"~",xname))
do.call(lm,list(data=quote(df),f1))
}
One of several attempts:
map(nested$data,lm_mod(Sepal.Length,Petal.Length))
Error:
Error in stats::model.frame(formula = df, data = ~Petal.Length, drop.unused.levels = TRUE) : object 'Sepal.Length' not found
It appears that my formula is interpreted as the data. How can I best implement this?
Upvotes: 1
Views: 288
Reputation: 13319
This fixed it: The problem was with my function definition that I later edited to explicitly state the data argument in the lm
call and thanks to @MrFlick too for pointing that out:
lm_mod<-function(df,xname,yname){
xname<-deparse(substitute(xname))
yname<-deparse(substitute(yname))
f1<-as.formula(paste(yname,"~",xname))
do.call(lm,list(data=quote(df),f1))
}
map(nested$data,lm_mod,Sepal.Length,Petal.Length)
Upvotes: 1