I used {{}}
to bulid a self-function in r.
I don't understand why this happend.
test.data = data.frame(pm10 = 1:5)
test.data
new.col.name = 'lag_pm10'
col = 'pm10'
test.data %>% # error
mutate({{new.col.name}} := lag({{col}}, 2))
test.data %>% # works
mutate({{new.col.name}} := lag(get(col), 2))
In my view, new.col.name
and col
would be parsed when I put them into {{}}
.
But the situation is that {{new.col.name}}
works fine and {{col}}
don't return what I expected.
Then I change {{col}}
into get(col)
and it works.
I don't know why.
In my opinion, the two objects' (new.col.name
and col
) value are all characters.
It should be the same when I use {{}}
to new.col.name
and col
.
I guess maybe {{new.col.name}}
become a variable name and {{col}}
become a parameter in mutate()
.
If that's the case.
Am I allowed to say that I can use {{}}
for any variable name and get()
for all arguments ?
CodePudding user response:
You can write this as a function passing unquoted variables and not as a string using the curly-curly {{
operator like this:
my_function <- function(test.data, new.col.name, col) {
test.data %>% # error
mutate({{new.col.name}} := lag({{col}}, 2))
}
my_function(test.data, lag_pm10, pm10)
Output:
pm10 lag_pm10
1 1 NA
2 2 NA
3 3 1
4 4 2
5 5 3