在 r 中的自定义函数中保留输入的变量名

retaining entered variable names inside a custom function in r

我想弄清楚如何保留在自定义函数中作为参数输入的变量名称。我想允许用户以两种不同的方式输入函数的参数 (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-02-19。

编辑

您正在寻找的是 deparse(substitute(x)),您的函数可以这样写:

prac.fn <- function(data = NULL, x, y, xlab=deparse(substitute(x)), ylab=deparse(substitute(y))) {

  if (!is.null(data)) {
    # if dataframe was provided
    df <- data.frame(x=data[,xlab], y=data[,ylab])

  } else {
    # if vectors were provided
    df <- data.frame(x = x, y = y)
    xlab <- gsub(".*\$", "", xlab)
    ylab <- gsub(".*\$", "", ylab)
  }
  print(df)
  print(xlab)
  print(ylab)
}

然后,prac.fn(x = iris[1:5,]$Species, y = iris[1:5,]$Sepal.Length) prac.fn(data = iris[1:5,], x = Species, y = Sepal.Length) 给出:

       x   y
1 setosa 5.1
2 setosa 4.9
3 setosa 4.7
4 setosa 4.6
5 setosa 5.0
[1] "Species"
[1] "Sepal.Length"

旧答案

我不确定是否正确理解了您的问题,但这里是您的代码的一个非常简化的版本,可能会对您有所帮助:

prac.fn <- function(data = NULL, xlab="x", ylab="y") {

  df <- data[, c(xlab, ylab)]
  colnames(df) <- c("x", "y")

  print(df)
  print(xlab)
  print(ylab)
}

prac.fn(data = iris[1:5,], xlab = "Species", ylab = "Sepal.Length")