使用dplyr mutate将列名传递给函数,而不使用折旧的mutate _

时间:2017-08-07 21:45:23

标签: r function dplyr

我意识到这似乎与已经提出的其他问题很接近,似乎在https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html上得到了解答 但我在下面显示的内容似乎遵循了这个建议,但没有成功。 这是数据:

 d<-tibble(y=c(1,2,3,NA))

首先有效:

my.f <- function(df,column_var){
  df %>%
  mutate(z = y) %>%
  filter(!is.na(z))
}
my.f(d,quo(z))

现在,我希望产生相同的结果,但不起作用:

my.f <- function(df,column_var){
  df %>%
  mutate(!!column_var = y) %>%
  filter(!is.na(!!column_var))
}
my.f(d,quo(z))

Error: unexpected '=' in:
"  df %>%
mutate(!!column_var ="

1 个答案:

答案 0 :(得分:2)

要设置变量名称,您需要在左侧使用字符串=而不是mutate中的quo_name

您可以使用zmy.f = function(df, column_var) { column_var = enquo(column_var) df %>% mutate(!!quo_name(column_var) := y) %>% filter( !is.na(!!column_var) ) } my.f(d, z) # A tibble: 3 x 2 y z <dbl> <dbl> 1 1 1 2 2 2 3 3 3 转换为列名称的字符串。

您的功能可能如下所示:

var prevPage = document.referrer; //The previous visited page.
var prevPageFolder = prevPage.split("/"); //Splitting the string to an array of substrings.
var pageNameIndex = prevPageFolder.length - 1;
prevPageFolder[pageNameIndex] = ""; //Select string to remove
route = prevPageFolder.join("/"); //Recreate the link without the name of the page.
//check to see if the link matches:
if (route == "www.mysite.com/something/somethingelse/") {
    //Whatever it is you want to do.
}