Reed
Reed

Reputation: 318

mutate_ formula eorrors programing with dplyr

I've got an issue in which I'm attempting to do something along the lines of:

df <- tibble(x=1:5, y = c(1,0,1,0,1))
zup <- function(df, zp.col){
  dz <- df %>%
  mutate_(z = ~x * !!zp.col)
}

foo <- zup(df, zp.col =  "y")

Where the resulting foo would have a column z containing the product of x and y. I'm pretty new to the programing side of dplyr, and I've read through the Programing with dplyr a couple of times but I can't seem to wrap my head around what I'm doing wrong. How I can get zp.col to unquote and be recognized as a column rather than a string. for instance if I use quo() too look at what's being passed through as suggested I can see:

zup <- function(df, zp.col){
  quo(dz <- df %>%
    mutate_(z = ~x + !!zp.col))
}

foo <- zup(df, zp.col =  "y")

> foo
<quosure: local>
~(dz <- df %>% mutate_(z = ~x + "y"))

Any help would be greatly appreciated!

Edit

Since the mutate_ has been replaced I changed to:

zup <- function(df, zp.col){
  dz <- df %>%
    mutate(z = ~x + !!zp.col)
}

foo <- zup(df, zp.col =  "y")

which returns:

 Error in mutate_impl(.data, dots) : 
  Column `z` is of unsupported type quoted call 

Even when changing to something like:

zup <- function(df, zp.col){
  out.col <- "z"
  dz <- df %>%
    mutate(!!out.col := ~x + !!zp.col)
}

foo <- zup(df, zp.col =  "y")

suggested at the end of the document I still receive the same error. Any suggestions?

Upvotes: 0

Views: 293

Answers (1)

Kevin Arseneau
Kevin Arseneau

Reputation: 6264

I think what you mean to do is use enquo with an expression rather than quo. This also allows bare column names as arguments into your function.

library(dplyr)

df <- tibble(x = 1:5, y = c(1, 0, 1, 0, 1))

zup <- function(df, zp.col) {

  quo.col <- enquo(zp.col)

  df %>% mutate(z = x * !!quo.col)

}

zup(df, y)

# # A tibble: 5 x 3
#       x     y     z
#   <int> <dbl> <dbl>
# 1     1     1     1
# 2     2     0     0
# 3     3     1     3
# 4     4     0     0
# 5     5     1     5

Upvotes: 1

Related Questions