【问题标题】:Function not working with a second argument when using tidyr::extract使用 tidyr::extract 时函数无法使用第二个参数
【发布时间】:2016-12-19 21:12:04
【问题描述】:

我写了一个从字符串中提取链接的函数。当我将数据框作为参数传递时它可以正常工作,但当我想将列名 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)

现在我想添加第二个参数,但它返回错误:

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

知道有什么问题吗?

【问题讨论】:

标签: r tidyr


【解决方案1】:

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

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

extractLinks(df, "string")

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多