1

I'm trying to use purrr::possibly() to skip over errors in my code, but for some reason, when I use possibly() here, it returns the output as if everything is an error.

Here's an example:

library(purrr)

add_things <- function(number) {
  
  new_number <- number + 1
  return(new_number)
  
}

possibly_add_things <- possibly(add_things, otherwise = NA)

# Works
map(c(1, 2, 3), possibly_add_things)
#> [[1]]
#> [1] 2
#> 
#> [[2]]
#> [1] 3
#> 
#> [[3]]
#> [1] 4

# Shouldn't be all NAs -- only the 2nd one
map(c(1, "hi", 3), possibly_add_things)
#> [[1]]
#> [1] NA
#> 
#> [[2]]
#> [1] NA
#> 
#> [[3]]
#> [1] NA

Created on 2021-05-11 by the reprex package (v1.0.0)

Any advice would be greatly appreciated.

Evan O.
  • 1,553
  • 2
  • 11
  • 20

1 Answers1

3

The issue is that a vector is defined by its single type and the magnitude or length. When, we use c, it is concatenating to a vector and based on the precedence of type, character is of higher precedence, thus all elements are converted to character. Instead, the input should be a list

map(list(1, 'hi', 3), possibly_add_things)
#[[1]]
#[1] 2

#[[2]]
#[1] NA

#[[3]]
#[1] 4
akrun
  • 874,273
  • 37
  • 540
  • 662