寫函數(shù)時(shí)經(jīng)常遇到需要傳遞外部變量到已知函數(shù)的情況玻粪,如下:
> my_func <- function(data, x, y, group) {
ggplot(data) +
geom_boxplot(aes(x = x, y = y, group = group))
}
> my_func(mtcars, x = "cyl", y = "mpg", group = "cyl")
這時(shí)候出的圖和你想象中不太一樣吧,準(zhǔn)確來講就是錯(cuò)的
odd
在之前選擇數(shù)據(jù)框中的列的時(shí)候就有類似的煩惱诬垂,但我沒深究劲室,曲線救國直接
[]
取的子集,但函數(shù)不行啊结窘,還是得探個(gè)究竟解決辦法如下:
> my_func <- function(data, x, y, group) {
ggplot(data) +
geom_boxplot(aes(x = !!sym(x), y = !!sym(y), group = !!sym(group)))
}
> my_func(mtcars, x = "cyl", y = "mpg", group = "cyl")
正常了吧
不放心的話很洋,可以看看正常代碼出的圖:
> ggplot(mtcars) + geom_boxplot(aes(x = cyl, y = mpg, group = cyl))
一模一樣
實(shí)質(zhì)上是變量引用的問題,之前以為是引號導(dǎo)致的隧枫,用
noquote()
去掉之后也不行喉磁,as.symbol()
它也不行,{{}}
它也不行悠垛。线定。stackoverflow上找到了答案,用!!sym()
它的詳細(xì)用法如下:
nse-force {rlang} R Documentation
Force parts of an expression
Description
It is sometimes useful to force early evaluation of part of an expression before it gets fully evaluated. The tidy eval framework provides several forcing operators for different use cases.
The bang-bang operator !! forces a single object. One common case for !! is to substitute an environment-variable (created with <-) with a data-variable (inside a data frame).
library(dplyr)
# The environment variable `var` refers to the data-variable
# `height`
var <- sym("height")
# We force `var`, which substitutes it with `height`
starwars %>%
summarise(avg = mean(!!var, na.rm = TRUE))
The big-bang operator !!! forces-splice a list of objects. The elements of the list are spliced in place, meaning that they each become one single argument.
vars <- syms(c("height", "mass"))
# Force-splicing is equivalent to supplying the elements separately
starwars %>% select(!!!vars)
starwars %>% select(height, mass)
The curly-curly operator {{ }} for function arguments is a bit special because it forces the function argument and immediately defuses it. The defused expression is substituted in place, ready to be evaluated in another context, such as the data frame.
In practice, this is useful when you have a data-variable in an env-variable (such as a function argument).
# Force-defuse all function arguments that might contain
# data-variables by embracing them with {{ }}
mean_by <- function(data, by, var) {
data %>%
group_by({{ by }}) %>%
summarise(avg = mean({{ var }}, na.rm = TRUE))
}
# The env-variables `by` and `var` are forced but defused.
# The data-variables they contain are evaluated by dplyr later on
# in data context.
iris %>% mean_by(by = Species, var = Sepal.Width)
Use qq_show() to experiment with forcing operators. qq_show() defuses its input, processes all forcing operators, and prints the result with expr_print() to reveal objects inlined in the expression by the forcing operators.
在寫公式的時(shí)候确买,有時(shí)候單純用paste連接不行斤讥,需要as.formula()
vegan::adonis(as.formula(paste("t(otuTab)", "~", var)), sub_design, method = method, permutations = 999) # Adonis test