Reputation: 4889
I am trying to create a custom function where some operation is carried out only on one column of the dataframe. But I want the function to work in such a way that it will output not only the column on which the operation was carried out, but also the entire dataframe from which that particular column was drawn. This is a very simple example of what I want to achieve:
# 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
Created on 2018-02-14 by the reprex package (v0.1.1.9000).
Upvotes: 2
Views: 293
Reputation: 5211
Just specify the columns you want to include in your select
call:
custom.fn <- function(data, x) {
df <- dplyr::select(.data = data,
x = !!rlang::enquo(x), y, z)
df$x <- df$x / 2
return(df)
}
If you don't want to name the rest of the columns explicitly, you can also use everything
:
df <- dplyr::select(.data = data, x = !!rlang::enquo(x), dplyr::everything())
Upvotes: 2