I am trying to use the standard evaluation in dplyr with functions in a global environment, but I am getting a "cannot find function" error. Here is the code
df <- data.frame(x = rnorm(10), y=rnorm(10))
test <- function(x) x^2
df %>% mutate_("mean(x)")
df %>% mutate_("test(x)")
I can get around this problem using df %>% mutate_(~test(x)), but I would like to use a string approach for various reasons. The main reason is that the user can pass a vector of variable names xto my function. I can use this vector to apply the same transformation to all variables, passing something like this as.list(sprintf('mean(%s, na.rm=TRUE)', x))to .dots. Here is the complete code
x <- c('x','y')
df %>% mutate_(.dots=as.list(sprintf('mean(%s, na.rm=TRUE)', x)))
df %>% mutate_(.dots=as.list(sprintf('test(%s, na.rm=TRUE)', x)))
, - ? , ? , ?
sessionInfo() output
R version 3.1.1 (2014-07-10)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] magrittr_1.5 dplyr_0.3.0.2 plyr_1.8.1 maptools_0.8-30 sp_1.0-16 Rcpp_0.11.3
[7] matrixStats_0.10.0 rgeos_0.3-8 stringr_0.6.2 mvtnorm_1.0-0 RcppArmadillo_0.4.400.0 Defaults_1.1-1
loaded via a namespace (and not attached):
[1] assertthat_0.1 DBI_0.3.1 foreign_0.8-61 grid_3.1.1 lattice_0.20-29 lazyeval_0.1.9 parallel_3.1.1 R.methodsS3_1.6.1
[9] tools_3.1.1