William Chiu
William Chiu

Reputation: 450

Using the output of purrr::safely()

Suppose I have a very large list in R. Some of the values are valid and some are invalid. The example uses a list with only 6 elements.

library(purrr)
library(dplyr)

myList <- list(-1, 0, 1, 2, 'poo', 'hi')

safe_log <- safely(log)

results <- myList %>%
  map(safe_log) %>%
  transpose()

allErrors <- results[['error']]

I have 3 questions:

  1. Using allErrors, which elements of myList are invalid? I'm looking for an integer vector that returns:
[1] 5 6
  1. Subset allError to show only the error messages. I expect this output:
[[5]]
<simpleError in .Primitive("log")(x, base): non-numeric argument to mathematical function>

[[6]]
<simpleError in .Primitive("log")(x, base): non-numeric argument to mathematical function>
  1. Subset myList for only the valid values. I want a new list that looks like this:
[[1]]
[1] -1

[[2]]
[1] 0

[[3]]
[1] 1

[[4]]
[1] 2

Upvotes: 2

Views: 255

Answers (1)

Marius
Marius

Reputation: 60220

  1. You can check which elements contain some kind of error using inherits:

    is_error = allErrors %>% map_lgl(~ inherits(., "error"))
    
  2. Once you've done that, subsetting the list is simple:

    which(is_error)
    allErrors[is_error]
    
  3. Same with subsetting to get the valid values:

    myList[! is_error]
    

Upvotes: 1

Related Questions