Search code examples
rpurrr

map_dbl fails when called with mean


I'm trying to replicate a simple example from R for Data Science, using the map functions.

This works: map_dbl(mtcars, median). But surprisingly, this doesn't: map_dbl(mtcars, mean). I get this error message:

> map_dbl(mtcars, mean)
Error in `map_dbl()`:
i In index: 1.
i With name: mpg.
Caused by error:
! Result must be length 1, not 0.

This map_dbl(mtcars, ~mean(.))solves the problem.

But why does map_dbl(mtcars, median)work while map_dbl(mtcars, mean)doesn't?


Solution

  • At a guess, you've assigned another value to mean somewhere along the way, e.g.:

    library(tidyverse)
    
    map_dbl(mtcars, mean)
    #>        mpg        cyl       disp         hp       drat         wt       qsec 
    #>  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750 
    #>         vs         am       gear       carb 
    #>   0.437500   0.406250   3.687500   2.812500
    map_dbl(mtcars, median)
    #>     mpg     cyl    disp      hp    drat      wt    qsec      vs      am    gear 
    #>  19.200   6.000 196.300 123.000   3.695   3.325  17.710   0.000   0.000   4.000 
    #>    carb 
    #>   2.000
    
    mean <- list()
    map_dbl(mtcars, mean)
    #> Error in `map_dbl()`:
    #> ℹ In index: 1.
    #> ℹ With name: mpg.
    #> Caused by error:
    #> ! Result must be length 1, not 32.
    
    map_dbl(mtcars, ~mean(.))
    #>        mpg        cyl       disp         hp       drat         wt       qsec 
    #>  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750 
    #>         vs         am       gear       carb 
    #>   0.437500   0.406250   3.687500   2.812500
    

    Created on 2023-06-16 with reprex v2.0.2

    To fix it try restarting R, making sure you aren't saving history. Or just clear out your global environment variables.