【发布时间】:2018-02-19 16:11:19
【问题描述】:
我试图弄清楚如何保留在自定义函数中作为参数输入的变量名。我想允许用户以(data = df, x = x, y = y) 或(data = NULL, x = df$x, y = df$y) 两种不同的方式向函数输入参数,并尝试在任何一种情况下准备标签。
# libraries needed
library(dplyr)
library(rlang)
library(datasets)
# defining the custom function
# allow two ways to enter the arguments to the function-
# (data = df, x = x, y = y) or (data = NULL, x = df$x, y = df$y)
prac.fn <- function(data = NULL, x, y) {
#===================== creating labels out of entered variables ===============
if (!is.null(data)) {
# if dataframe is provided
lab.df <- colnames(dplyr::select(.data = data,
!!rlang::enquo(x),
!!rlang::enquo(y)))
xlab <- lab.df[1]
ylab <- lab.df[2]
} else {
# if vectors were provided
# split the name of the entered variable by `$` sign and
# select the second part of the split string
xlab <- strsplit(quote(x), "$", fixed = TRUE)[[1]][[2]]
ylab <- strsplit(quote(y), "$", fixed = TRUE)[[1]][[2]]
}
print(xlab)
print(ylab)
}
# checking if the code works
# using the `data` argument (this works!)
prac.fn(data = iris, x = Species, y = Sepal.Length)
#> [1] "Species"
#> [1] "Sepal.Length"
# without using the `data` argument (this doesn't work)
prac.fn(x = iris$Species, y = iris$Sepal.Length)
#> Error in strsplit(quote(x), "$", fixed = TRUE): non-character argument
# desired output
# xlab should be assigned the character 'Species'
# xlab should be assigned the character 'Sepal.Length'
由reprex package (v0.2.0) 于 2018 年 2 月 19 日创建。
【问题讨论】: