Error when using purrr's map and possibly

二次信任 提交于 2021-02-11 00:10:36

问题


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?


回答1:


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_ ))


来源:https://stackoverflow.com/questions/53244087/error-when-using-purrrs-map-and-possibly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!