Reading the Programming with dplyr guide, I get a unexpected error.
In fact, trying the examples with summarize
works quite right, but if I try similar things with mutate
, the code won't run.
Here is my code :
df = data.frame(A=c(464,3465,48,3415,357,21,657), B=c(12,15,985,35,67,13,467))
df %>%
mutate(x = A-B) %>%
pull(x)
#returns the good output :
#[1] 452 3450 -937 3380 290 8 190
get.diff = function(var1, var2, data=df){
var1 = enquo(var1)
var2 = enquo(var2)
data %>%
mutate(x = (!!var1 - !!var2)) %>%
pull(x)
}
get.diff(A, B)
returns an error
Here is the error :
Error in !var2 : invalid argument type
I tried a lot of thing, but this is the closest I got to the guide samples.
What did I miss ?
You just need parentheses around each "bang bang" / unquoting (!!varX
) :
mutate(x = ((!!var1) - (!!var2))) %>%
Full code:
df = data.frame(A=c(464,3465,48,3415,357,21,657), B=c(12,15,985,35,67,13,467))
df %>%
dplyr::mutate(x = A-B) %>%
pull(x)
#returns the good output :
#[1] 452 3450 -937 3380 290 8 190
get.diff = function(var1, var2, data=df){
var1 = enquo(var1)
var2 = enquo(var2)
data %>%
dplyr::mutate(x = ((!!var1) - (!!var2))) %>%
pull(x)
}
get.diff(A, B)
[1] 452 3450 -937 3380 290 8 190