使用 tidyr::extract 时函数无法使用第二个参数

Function not working with a second argument when using tidyr::extract

我写了一个函数来从字符串中提取链接。当我将数据帧作为参数传递时,它工作正常,但当我想将列名 string 作为第二个参数传递时,它工作正常。

一个参数的工作函数:

library(tidyr)     
extractLinks <- function(x) {

  # get all links in new column "url"
  df <- tidyr::extract(x, string, "url", "(http.*)")

  #get clean links and domains
  df <- tidyr::extract(df, url, c("site", "domain"), "(http.*\.(com|co.uk|net))", remove = F)

  return(df)
}

extractLinks(df, string)

现在我想添加第二个参数,但是returns一个错误:

Error in names(l) <- enc2utf8(into) : 
  'names' attribute [1] must be the same length as the vector [0] 

这是我的函数,有两个参数:

extractLinks <- function(x, y) {

  # get all links in new column "url"
  df <- tidyr::extract(x, y, "url", "(http.*)")

  #get clean links and domains
  df <- tidyr::extract(df, url, c("site", "domain"), "(http.*\.(de|com|at|ch|ly|co.uk|net))", remove = F)
  return(df)
}

extractLinks(df, string)

对于复制,示例数据框:

string
my text in front of the link http://www.domain.com
my text in front of the link http://www.domain.com
my text in front of the link http://www.domain.com

知道哪里出了问题吗?

您需要使用标准评估变体 extract_() 并将您的第二个参数转换为字符串:

  # get all links in new column "url"
  df <- tidyr::extract_(x, y, "url", "(http.*)")

extractLinks(df, "string")