2

I'm trying to run a looped chi-square dataframe. I'm using map and possibly, both from purrr, to allow the loop to run even if an error is thrown. Somewhere in my data.frame, I have a column that apparently has less than two values -- I can't find it. But, that's why I'm trying to run possibly. But, I'm now getting an error that says: Can't convert a list to function. I'm not sure how to reconcile this error. I've gotten a replicable example that throws the error using the mtcars data.frame.

library(tidyverse)

df <- mtcars %>% 
  mutate(z = 0)

map(df, function(x){
  possibly(chisq.test(df$gear, x), otherwise = NA)
})

# Error: Can't convert a list to function
# In addition: Warning message:
# In chisq.test(df$gear, x) :
#  Show Traceback
#  
#  Rerun with Debug
#  Error: Can't convert a list to function 

Any advice?

elliot
  • 1,844
  • 16
  • 45
  • Would you accept as an answer, something that returns the total number of unique values that each variable in your dataframe has? – Henry Cyranka Nov 10 '18 at 23:08
  • This won't solve your whole problem, but I believe you need `NA_real_` for `otherwise` – Fons MA Nov 10 '18 at 23:09

1 Answers1

4

The problem is in how you use possibly. possibly needs to wrap the function that generates the error. You are thinking that it this would be chisq.test. Not a wrong thought, because that would be my first choice as well. But inside map this is not the one that throws the error. The function you created for the .f part of the map function throws the error. I hope my explanation is clear, but check following examples to make it a bit more clear in code.

example 1:

# Catch error of chisq.test by wrapping possibly around it
map(df, possibly(chisq.test, NA_real_), x = df$gear)

$`mpg`

    Pearson's Chi-squared test

data:  df$gear and .x[[i]]
X-squared = 54.667, df = 48, p-value = 0.2362

......

$z
[1] NA

Example 2 equal results:

# Catch error of created function inside map. wrap possibly around it
map(df, possibly(function(x) {
  chisq.test(df$gear, x)}
  , NA_real_ ))
phiver
  • 23,048
  • 14
  • 44
  • 56