首页 > 解决方案 > R函数解析strsplit“下标越界”中的返回错误

问题描述

我正在使用 R 为一列 HTML 页面提取域名。为此,我创建了一个函数“域”。它似乎工作正常,直到它击中以“mailto:person@example.com”形式出现的页面。这些显然是电子邮件的链接。我仍然想将这些合并到我的数据集中,但我得到的错误是:“strsplit 中的错误(gsub(” http://|https://|www\。”,“”,x),“/”) [[c(1, 1)]] : 下标越界"

如何修改此代码以绕过“mailto”页面?

这是我的功能

domain <- function(x) strsplit(gsub("http://|https://|www\\.","", x),"/")[[c(1,1)]]

这是我的命令

mainpagelevel3$url <- sapply(mainpagelevel3$url, domain)

我在一组不包含“mailto:”页面的 url 上运行了这段代码,它工作得很好,所以我认为这一定是它被卡住的地方。我不介意它是否导致“person@example.com”或保持原样。

标签: rhtml-parsing

解决方案


We could try to write an if condition to check for strings which start with "mailto" and have "@" in them (this can be made more strict if needed). So the function might look like

domain <- function(x) {
   if(grepl("^mailto:.*@.*", x)) x 
      else strsplit(gsub("http://|https://|www\\.","", x),"/")[[c(1,1)]]
}

and then use sapply as usual

mainpagelevel3$url <- sapply(mainpagelevel3$url, domain)

推荐阅读