If I have a column in a data.frame
that has the same name as one of the arguments to my function, the column name is used when trying to mutate
or filter
.
Is there a way to explicitly use the function parameter?
Reproducible example:
my_function <- function(x) {
my_tib <- tribble(
~x, ~y,
1, 5,
2, 10,
3, 15
)
my_tib %>%
mutate(z = x * y)
}
my_function(x=100)
## A tibble: 3 x 3
# x y z
# <dbl> <dbl> <dbl>
#1 1 5 5
#2 2 10 20
#3 3 15 45
Desired result:
my_function(x=100)
## A tibble: 3 x 3
# x y z
# <dbl> <dbl> <dbl>
#1 1 5 500
#2 2 10 1000
#3 3 15 1500
You can use the {{
operator although avoiding the conflict in the first place seems a better way to avoid possible headaches.
library(dplyr)
my_function <- function(x) {
my_tib <- tribble(
~x, ~y,
1, 5,
2, 10,
3, 15
)
my_tib %>%
mutate(z = {{x}} * y)
}
my_function(100)
# A tibble: 3 x 3
x y z
<dbl> <dbl> <dbl>
1 1 5 500
2 2 10 1000
3 3 15 1500