Standard grade using mutate using lazyeval

I am trying to make my own function by wrapping dplyr functions.

I have a list of data frames, and I would like to change the levels of the specified variable with the given labels (both must be functional parameters).

This is what I have 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 work, and I just don’t understand why ... Do you know what I am missing? Thank.

+4
source share
1 answer

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
+3
source

All Articles