[英]how to pass a column name to a function
I have written a function that does a few analysis including calculating a measure called "Net Promoter Score" using NPS
package . 我编写了一个函数,进行了一些分析,包括使用NPS
软件包计算称为“ Net Promoter Score”的度量。
library(dplyr)
library(tidyr)
library(NPS)
df<-data.frame(score = sample(c(0:10),15,replace=TRUE),
variable = sample(c('A', 'B', 'C'),15,replace=TRUE)
)
analyzer <- function(df,var, sco){
df %>% group_by_(var) %>% transmute(n= nps(sco)) %>% unique()
}
analyzer(df,'variable','score')
This returns NA
for all levels of variable. 这将返回所有变量级别的NA
。
Now dplyr functions have a way of dealing with x
being handed to them as character(ie, their _
version which I've used here), but the nps
function doesn't. 现在,dplyr函数可以处理以字符形式传递给x
的方法(即,我在这里使用的_
版本),但是nps
函数没有。 I also tried passing score column as nps(.[[score]])
but this returns the NPS for the whole column and doesn't break it down by group_by levels. 我还尝试将分数列传递为nps(.[[score]])
但这会返回整个列的NPS,并且不会按group_by级别对其进行细分。
You can use the rlang package and then uquote your variables with !! 您可以使用rlang包,然后用!!括起来!
library(dplyr)
library(tidyr)
library(NPS)
library(rlang)
df<-data.frame(score = sample(c(0:10),15,replace=TRUE),
variable = sample(c('A', 'B', 'C'),15,replace=TRUE)
)
analyzer <- function(df,var, sco){
var <- rlang::enquo(var)
sco <- rlang::enquo(sco)
df %>% group_by(!!var) %>% transmute(n= nps(!!sco)) %>% unique()
}
analyzer(df, variable,score)
It's because the inputs to functions are not getting evaluated properly- 这是因为未正确评估函数的输入-
(Note that the way it is implemented here, the function will work irrespective of whether you enter a bare expression x = x
or a character x = "x"
) (请注意,此处实现该方法的方法将起作用,无论您输入的是裸表达式x = x
还是字符x = "x"
)
library(dplyr)
library(tidyr)
library(NPS)
set.seed(123)
# data
df <- data.frame(score = sample(c(0:10), 15, replace = TRUE),
variable = sample(c('A', 'B', 'C'), 15, replace = TRUE))
# custom function
analyzer <- function(df, var, sco) {
var <- rlang::ensym(var)
sco <- rlang::ensym(sco)
df <- df %>%
group_by(., !!rlang::enquo(var)) %>%
transmute(., n = NPS::nps(!!rlang::enquo(sco))) %>%
unique()
return(df)
}
# using function
analyzer(df, 'variable', 'score')
#> # A tibble: 3 x 2
#> # Groups: variable [3]
#> variable n
#> <fct> <dbl>
#> 1 C -0.333
#> 2 A -0.4
#> 3 B -0.25
Created on 2018-11-18 by the reprex package (v0.2.1) 由reprex软件包 (v0.2.1)创建于2018-11-18
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.