rdplyrstandard-evaluation

Standard Evaluation with mutate using lazyeval


I'm trying to make my own function wrapping dplyr functions.

I have a list of dataframes and I would like to modify the levels of a specified variable with given labels (both should be function's parameters).

This is what I tried so far :

library(plyr); library(dplyr)

groups <- list(label1 = "setosa", label2 = c("virginica", "versicolor"))

iris$Species <- as.character(iris$Species)
x <- lapply(1:5, function(x) iris)

f <- function(datas, fillVar, groups) {

  fillStr <- deparse(substitute(fillVar))

  datas <- llply(datas, function(x) {
    x <- mutate_(x, .dots = setNames(list(lazyeval::interp(~ factor(var), var = substitute(fillStr))), fillStr))
    levels(x[,fillStr]) <- groups
    return(x)})

  return(datas)
}

f(x, Species, groups)

 Error in mutate_impl(.data, dots) : object 'Species' not found 

But I can't make it works and I just don't understand why... Do you know what I am missing ? Thanks.


Solution

  • Try

    f1 <- function(datas, fillVar, groups) {
      fillStr <- deparse(substitute(fillVar))
      datas <- llply(datas, function(x) {
         x <- mutate_(x, .dots = setNames(list(lazyeval::interp(~ factor(var),
                    var = as.name(fillStr))), fillStr))
        levels(x[fillStr]) <- groups
        x})
       return(datas)
    }
    
     identical(f(x, 'Species', groups), f1(x, Species, groups))
     #[1] TRUE