gpt4 book ai didi

r - 如何强制 For loop() 或 lapply() 在 R 中运行并显示错误消息

转载 作者:行者123 更新时间:2023-12-04 09:30:48 24 4
gpt4 key购买 nike

在此代码上,当我使用 for 循环或函数 lapply 时,出现以下错误

"Error in get_entrypoint (debug_port):
Cannot connect R to Chrome. Please retry. "


library(rvest)
library(xml2) #pull html data
library(selectr) #for xpath element

url_stackoverflow_rmarkdown <-
'https://stackoverflow.com/questions/tagged/r-markdown?tab=votes&pagesize=50'

web_page <- read_html(url_stackoverflow_rmarkdown)

questions_per_page <- html_text(html_nodes(web_page, ".page-numbers.current"))[1]

link_questions <- html_attr(html_nodes(web_page, ".question-hyperlink")[1:questions_per_page],
"href")

setwd("~/WebScraping_chrome_print_to_pdf")

for (i in 1:length(link_questions)) {
question_to_pdf <- paste0("https://stackoverflow.com",
link_questions[i])

pagedown::chrome_print(question_to_pdf)
}

是否可以建立 for loop()或使用 lapply从中断的地方重复代码?也就是说,从最后一个 i不破坏代码的值(value)?

非常感谢

最佳答案

我编辑了@Rui Barradas 关于tryCatch() 的想法.
您可以尝试执行以下操作。IsValues将获得链接值或错误 i s。

IsValues <- list()
for (i in 1:length(link_questions)) {
question_to_pdf <- paste0("https://stackoverflow.com",
link_questions[i])

IsValues[[i]] <- tryCatch(
{
message(paste("Converting", i))

pagedown::chrome_print(question_to_pdf)
},
error=function(cond) {
message(paste("Cannot convert", i))
# Choose a return value in case of error
return(i)
})
}

然后,您可以重新绑定(bind)您的值并提取错误的 i年代:
do.call(rbind, IsValues)[!grepl("\\.pdf$", do.call(rbind, IsValues))]

[1] "3" "5" "19" "31"

您可以阅读有关 tryCatch() 的更多信息在 this answer .

关于r - 如何强制 For loop() 或 lapply() 在 R 中运行并显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59273046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com