gupta
gupta

Reputation: 51

How to pass a column name into a custom function, which uses dplyr?

I've written this function which just replaced each value in a data table's column with its substring:

substrColName <- function(df, colName, start) {
    df %>% mutate(colName = substr(colName, start=start, stop=nchar(colName)))
}

But every time I try running it I get the error:

Error in as.character(x) : cannot coerce type 'closure' to vector of type 'character'

Now I've done a lot of research on why it won't work but I can't figure it out. I've read on some stuff with standard evaluations and lazyeval but nothing I try seems to work. Any help?

Thanks

Upvotes: 2

Views: 141

Answers (1)

gupta
gupta

Reputation: 51

Thanks, @ycw, that was a nice read. Got it working now after working through the article. This was the solution at the end of the day:

substrColName <- function(df, colName, start) {
    colNameQuo <- enquo(colName)
    df %>% mutate(!!quo_name(colNameQuo) := substr(!!colNameQuo, start=start,stop=nchar(!!colNameQuo)))
}

And this is ycw's comment.

Upvotes: 2

Related Questions