【发布时间】: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
知道有什么问题吗?
【问题讨论】:
-
所以
df是一个data.frame,其中有一列名为string?它有助于将数据放入reproducible format 以使其更清晰。看起来您希望函数执行非标准评估,因为您想延迟对y值的评估。查看dplyr NSE vignette 或Advanced R - Non Standard Evaluation 部分。这通常比它的价值更麻烦。