purrr map_df() issues with infer

I am having some issues with purrr here. Not sure what the issue is. I have also tried using {{xval}} and get(), but they don't seem to work. It is probably just something silly that I've done but can't figure out.

library(tidyverse)
library(infer)

# this works --------
# from https://infer.tidymodels.org/articles/chi_squared.html
gss %>%
  specify(college ~ finrela) %>%
  hypothesise(null = "independence") %>%
  calculate(stat = "Chisq")


# this does not!!! ----
gss_vec <- c("sex", "partyid", "income", "class", "finrela") %>% 
  set_names()

chi_sq_func <- function(xval){
  gss %>% 
    specify(college ~ .data[[xval]]) %>%
    hypothesise(null = "independence") %>%
    calculate(stat = "Chisq")
}

map_df(.x = gss_vec,
       .f = chi_sq_func(.x),
       .id = "variable")

Error: The explanatory variable [[ cannot be found in this dataframe.The explanatory variable .data cannot be found in this dataframe.The explanatory variable xval cannot be found in this dataframe.

I think the .data pronoun doesnt work in that context, so I used a more general tidyeval approach.
However, this meant that I attempt the calculation on all the variables, and some of them required setting success="degree", and one was an ordered factor that I had to throw away the ordering to get any output.


gss_vec <- c("sex", "partyid", "income", "class", "finrela") %>% 
  set_names()

chi_sq_func <- function(xval){
  if(is.ordered(gss[[xval]]))
    gss[[xval]] <- factor(gss[[xval]],ordered = FALSE)
  
  eval(expr(specify(x = gss,
                    formula = college ~ !!sym(xval),
                    success="degree"))) %>% 
    hypothesise(null = "independence") %>%
    calculate(stat = "Chisq")
}

map_df(.x = gss_vec,
       .f = ~chi_sq_func(.x),
       .id = "variable")
2 Likes

Great. Thanks for your help.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.