【问题标题】:Iteration over a non-existing file in the directory迭代目录中不存在的文件
【发布时间】:2022-01-24 10:24:25
【问题描述】:

我的目录中有大约五个文件要在 r 中读取。每个文件都有一个名称模式:“filex.html”,其中 x=1,2,3 等等。但是,缺少一些文件。我想创建一个循环来读取所有文件,并且每当任何文件不存在时,循环都应该跳转到序列中的下一个文件。但是,只要遇到第一个不存在的文件,我的循环就会停止。

下面是循环。

ids = c(1:10)

for (i in ids) {
  myurl = paste("mypage",i,".html") 
  myurl = gsub(" ","",myurl)
  pointer = read_html(myurl)
   if(is_null(pointer)){
     next
   }
    
    
}

这是错误。

Error: 'mypage3.html' does not exist in current working directory ('E:/My_projects/mydb').

如何在不存在的文件上迭代我的循环?

【问题讨论】:

    标签: r loops for-loop iteration


    【解决方案1】:

    不要循环遍历可能包含不存在文件的ids 向量,而是尝试在从list.files() 获得的实际文件列表上使用lapply

    您可以使用模式仅获取带有list.files(pattern = "*.html")html 文件。

    这是一个例子

    html_files = list.files(pattern = "*.html").
    
    lapply(html_files, function(x) {
        pointer = read_html(x)
    }
    

    【讨论】:

    • 如果我想先从各自的 URL 下载 HTML 文件,它也可以吗?
    • 这将列出您工作目录中的所有 HTML 文件,然后您将对其进行循环。您可以将其与 lapply 语句中的任何函数一起使用。
    猜你喜欢
    • 2018-09-01
    • 2021-03-27
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多