0

I'm trying to build a function using mutate inside. The code is as follows

pre_process_corpora <- function(data, column, new_column){
    data %>% mutate(new_column = tolower(column))
}

However, when running the function, I got below error and I still could not figure out why.

 Error in eval(lhs, parent, parent) : object 'x' not found

I was also trying to do another way to build a function with below syntax

data$new_column <- tolower(data$column)

However, I received below error message

$ operator is invalid for atomic vectors

Any tip / insight is much appreciated!

alistaire
  • 42,459
  • 4
  • 77
  • 117
  • 4
    Programming with dplyr requires [additional syntax](https://dplyr.tidyverse.org/articles/programming.html). And you'll need to show data for why the second one is failing. – alistaire Sep 24 '18 at 14:43
  • `$ operator is invalid for atomic vectors` are you sure that `data` is a `data.frame`? You get this error usually because it's not. – RLave Sep 24 '18 at 14:43
  • 1
    How exactly are you calling the `pre_process_corpora` function. When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Sep 24 '18 at 14:43
  • Yes, the data is a data.frame. – Nelson Chou Sep 24 '18 at 14:52

1 Answers1

3

Staying with dplyr and rlang, maybe something like this?

library(dplyr)
library(rlang)

pre_process_corpora<-function(data, column, new_column){
    column <- enquo(column)
    new_column <- quo_name(enquo(new_column))
    data %>% mutate(!!new_column := tolower(!!column))
}

d <- data.frame(x = LETTERS[1:5],stringsAsFactors = FALSE)

pre_process_corpora(d,x,foo)
joran
  • 169,992
  • 32
  • 429
  • 468