Reputation: 450
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:
allErrors
, which elements of myList
are invalid? I'm looking for an integer vector that returns:[1] 5 6
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>
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
Reputation: 60220
You can check which elements contain some kind of error using inherits
:
is_error = allErrors %>% map_lgl(~ inherits(., "error"))
Once you've done that, subsetting the list is simple:
which(is_error)
allErrors[is_error]
Same with subsetting to get the valid values:
myList[! is_error]
Upvotes: 1