使用 tidyverse 和 ggplot2 (ggpmisc) 时如何忽略 cor.test:“有限观察不足”并继续

How to ignore cor.test:“not enough finite observations” and continue, when using tidyverse and ggplot2 (ggpmisc)

我有以下工作玩具示例:

trunctiris <- iris [1:102,] 
analysis <- trunctiris %>%
  group_by(Species) %>%
  nest() %>%
  mutate(model = map(data, ~lm(Sepal.Length ~ Sepal.Width, data = .)),
         cor = map(data, ~tidy(cor.test(.x$Sepal.Length, .x$Sepal.Width), 3)))

stats <- analysis %>%
  unnest(cor)

ggplot(trunctiris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(shape = 21) +
  geom_text(data = stats, aes(label = sprintf("r = %s", round(estimate, 3)), x = 7, y = 4)) +
  geom_text(data = stats, aes(label = sprintf("p = %s", round(p.value, 3)),  x = 7, y = 3.8)) +
  geom_smooth(method = "lm", formula = y ~ x) +
  stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")),
               formula = y ~ x,
               parse = TRUE) +
  facet_wrap(~Species)

代码在另一个问题中提供。但是,我无法使其与我的数据一起使用。问题是我有一些(不是全部)组的观察值少于 3 个,因此,在 "analysis" 部分 R returns:

mutate_impl(.data, dots) 中的错误:有限观察不足

这与组中没有足够的观察值这一事实有关(在这种情况下:virginica)。我想解决这个问题,我试过 'try(if nrow(data) >= 2)' 或类似的.. 如下所示:

analysis <- iris %>% 
group_by(Species) %>% 
nest() %>% mutate(model = map(data, ~lm (Sepal.Length ~ Sepal.Width, data = .)), 
    cor = if_else( nrow(data) <= 2 , warning ("Must have at least 3 rows of data"), 
        (map(data, ~tidy(cor.test(.x$Sepal.Length, .x$Sepal.Width), 3)))))

哪个returns:

mutate_impl(.data, dots) 中的错误:没有足够的有限观察 另外: 警告信息: 在 if_else(nrow(列表(列表(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, : 必须至少有3行数据

有人知道解决这个问题的简单方法吗?我想跳过有问题的小组并继续前进。

非常感谢和抱歉我非常基本的 R 技能。

purrr::safelypurrr::possibly 允许在 mapping 时轻松防止错误。在这种情况下,一个好的策略是将对 tidy(cor.test(... 的调用包装在 possibly 和 return 一个空的 data.frame 中,如果发生错误

library(purrr)
analysis <- trunctiris %>%
  group_by(Species) %>%
  nest() %>%
  mutate(
    model = map(data, ~lm(Sepal.Length ~ Sepal.Width, data = .)),
    cor = map(data, possibly(
      ~tidy(cor.test(.x$Sepal.Length, .x$Sepal.Width), 3), otherwise = data.frame())
    )
  )
# A tibble: 3 × 4
     Species              data    model                  cor
      <fctr>            <list>   <list>               <list>
1     setosa <tibble [50 × 4]> <S3: lm> <data.frame [1 × 8]>
2 versicolor <tibble [50 × 4]> <S3: lm> <data.frame [1 × 8]>
3  virginica  <tibble [2 × 4]> <S3: lm> <data.frame [0 × 0]> #<- Note the empty df here

变成:

unnest(analysis)
# A tibble: 2 × 9
     Species  estimate statistic      p.value parameter  conf.low conf.high
      <fctr>     <dbl>     <dbl>        <dbl>     <int>     <dbl>     <dbl>
1     setosa 0.7425467  7.680738 6.709843e-10        48 0.5851391 0.8460314
2 versicolor 0.5259107  4.283887 8.771860e-05        48 0.2900175 0.7015599
# ... with 2 more variables: method <fctr>, alternative <fctr>

因此出错的组已成功从最终结果中删除。