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

时间:2018-02-19 16:11:20

标签: r eval rlang

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

1 个答案:

答案 0 :(得分:1)

修改

您正在寻找的是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"

OLD ANSWER

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

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")