使用 rlang select 整个数据框,而不仅仅是一列

using rlang to select the entire dataframe and not just one column

我正在尝试创建一个自定义函数,其中某些操作仅在数据框的一列上执行。但我希望该函数以这样一种方式工作,即它不仅会输出执行操作的列,还会输出绘制该特定列的整个数据框。这是我想要实现的一个非常简单的例子:

# libraries needed
library(dplyr)
library(rlang)

# creating a dataframe
data <-
  as.data.frame(cbind(
    x = rnorm(5),
    y = rnorm(5),
    z = rnorm(5)
  ))

# defining the custom function
custom.fn <- function(data, x) {
  df <- dplyr::select(.data = data,
                      x = !!rlang::enquo(x)) # how can I also retain all the other columns in the dataframe apart from x?
  df$x <- df$x / 2
  return(df)
}

# calling the function (also want y and z here in the ouput)
custom.fn(data = data, x = x)
#>             x
#> 1  0.49917536
#> 2 -0.03373202
#> 3 -1.24845349
#> 4 -0.15809688
#> 5  0.11237030

reprex 创建于 2018-02-14 包 (v0.1.1.9000).

只需指定要包含在 select 调用中的列:

custom.fn <- function(data, x) {
  df <- dplyr::select(.data = data,
                      x = !!rlang::enquo(x), y, z)
  df$x <- df$x / 2
  return(df)
}

如果您不想明确命名其余列,您也可以使用 everything:

df <- dplyr::select(.data = data, x = !!rlang::enquo(x), dplyr::everything())