How to tell lapply to ignore an error and process the next thing in the list?
Use a tryCatch
expression around the function that can throw the error message:
testFunction <- function (date_in) {
return(tryCatch(as.Date(date_in), error=function(e) NULL))
}
The nice thing about the tryCatch
function is that you can decide what to do in the case of an error (in this case, return NULL
).
> lapply(dates2, testFunction)
[[1]]
[1] "2010-04-06"
[[2]]
NULL
[[3]]
[1] "2010-04-08"
R allow error in lapply
You need to provide lapply
with a function:
lapply_with_error <- function(X,FUN,...){
lapply(X, function(x, ...) tryCatch(FUN(x, ...),
error=function(e) NULL))
}
How to force a For loop() or lapply() to run with error message in R
Based on your example, it looks like you have two errors to contend with. The first error is the one you mention in your question. It is also the most frequent error:
Error in get_entrypoint (debug_port): Cannot connect R to Chrome. Please retry.
The second error arises when there are links in the HTML that return 404:
Failed to generate output. Reason: Failed to open https://lh3.googleusercontent.com/-bwcos_zylKg/AAAAAAAAAAI/AAAAAAAAAAA/AAnnY7o18NuEdWnDEck_qPpn-lu21VTdfw/mo/photo.jpg?sz=32 (HTTP status code: 404)
The key phrase in the first error is "Please retry". As far as I can tell, chrome_print
sometimes has issues connecting to Chrome. It seems to be fairly random, i.e. failed connections in one run will be fine in the next, and vice versa. The easiest way to get around this issue is to just keep trying until it connects.
I can't come up with any fix for the second error. However, it doesn't seem to come up very often, so it might make sense to just record it and skip to the next URL.
Using the following code I'm able to print 48 of 50 pages. The only two I can't get to work have the 404 issue I describe above. Note that I use purrr::safely
to catch errors. Base R's tryCatch
will also work fine, but I find safely
to be a little more convient. That said, in the end it's really just a matter of preference.
Also note that I've dealt with the connection error by utilizing repeat
within the for loop. R will keep trying to connect to Chrome and print until it is either successful, or some other error pops up. I didn't need it, but you might want to include a counter to set an upper threshold for the number of connection attempts:
quest_urls <- paste0("https://stackoverflow.com", link_questions)
errors <- NULL
safe_print <- purrr::safely(pagedown::chrome_print)
for (qurl in quest_urls){
repeat {
output <- safe_print(qurl)
if (is.null(output$error)) break
else if (grepl("retry", output$error$message)) next
else {errors <- c(errors, `names<-`(output$error$message, qurl)); break}
}
}
R TryCatch not working with lapply
I believe your first example should work in principle, but don't understand what you are doing with the ellipses there.
Here is a simple minimal example:
foo <- function(x) {
if (x == 6) stop("no 6 for you")
x
}
l <- list(1, 5, 6, 10)
lapply(l, foo)
# Error in FUN(X[[i]], ...) : no 6 for you
bar <- function(x) tryCatch(foo(x), error = function(e) e)
lapply(l, bar)
#[[1]]
#[1] 1
#
#[[2]]
#[1] 5
#
#[[3]]
#<simpleError in foo(x): no 6 for you>
#
#[[4]]
#[1] 10
baz <- function(x) tryCatch({
if (x == 6) stop("no 6 for you")
x
}, error = function(e) e)
lapply(l, baz)
#also works
For-loop and Lapply: Same function gives different results
In your attempt you are giving values of n
and r
to be length(exampleList)
. However, it should be equal to length of each individual element in the list.
lapply(exampleList, function(x)
gtools::permutations(n = length(x), r = length(x), v = x))
#[[1]]
# [,1] [,2]
#[1,] "COMBINATIONS" "RETURN"
#[2,] "RETURN" "COMBINATIONS"
#[[2]]
# [,1] [,2] [,3]
#[1,] 1 2 3
#[2,] 1 3 2
#[3,] 2 1 3
#[4,] 2 3 1
#[5,] 3 1 2
#[6,] 3 2 1
#[[3]]
# [,1]
#[1,] "PLEASE WORK"
You can also write this with Map
Map(function(x, y) gtools::permutations(n = y, r = y, v = x),
exampleList, lengths(exampleList))
Apply a function to a list of object and corresponding strings
You may try the following, using mapply
:
myfuntion <- function(object,filename) {
paste(object, filename)
}
input <- list("a","b","c")
filename_list <- c("a","b","c")
mapply(myfuntion, input, filename_list)
#> [1] "a a" "b b" "c c"
Related Topics
Remove Multiple Objects with Rm()
Finding Overlaps Between Interval Sets/Efficient Overlap Joins
Growing a Data.Frame in a Memory-Efficient Manner
Collapsing Data Frame by Selecting One Row Per Group
Floating Point Less-Than-Equal Comparisons After Addition and Substraction
Creating "Radar Chart" (A.K.A. Star Plot; Spider Plot) Using Ggplot2 in R
Ggplot Side by Side Geom_Bar()
Problems Installing the Devtools Package
How to Geocode a Simple Address Using Data Science Toolbox
Linear Regression Loop for Each Independent Variable Individually Against Dependent
Force Character Vector Encoding from "Unknown" to "Utf-8" in R
Dplyr - Using Column Names as Function Arguments
Remove Groups with Less Than Three Unique Observations
Problems When Trying to Load a Package in R Due to Rjava