【问题标题】:Error when using purrr's map and possibly使用 purrr 的地图时出错,可能
【发布时间】:2018-11-10 22:33:20
【问题描述】:

我正在尝试运行循环卡方dataframe。我正在使用来自purrrmappossibly,即使抛出错误也允许循环运行。在我的 data.frame 的某个地方,我有一列显然少于两个值——我找不到它。但是,这就是我尝试运行possibly 的原因。但是,我现在收到一条错误消息:无法将列表转换为函数。我不确定如何调和这个错误。我得到了一个使用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 

有什么建议吗?

【问题讨论】:

  • 您是否接受返回数据框中每个变量具有的唯一值总数的答案?
  • 这并不能解决你的全部问题,但我相信你需要NA_real_ for otherwise

标签: r purrr


【解决方案1】:

问题在于你如何使用possiblypossibly 需要包装产生错误的函数。您认为这将是 chisq.test。这不是一个错误的想法,因为这也是我的第一选择。但是在地图内部,这不是引发错误的那个。您为 map 函数的 .f 部分创建的函数会引发错误。我希望我的解释清楚,但请检查以下示例以使其在代码中更加清晰。

示例 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

示例 2 相同的结果:

# Catch error of created function inside map. wrap possibly around it
map(df, possibly(function(x) {
  chisq.test(df$gear, x)}
  , NA_real_ ))

【讨论】:

  • 谢谢,这解决了问题并在我的数据库上完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 2019-01-18
  • 2020-12-23
相关资源
最近更新 更多