dplyr: passing variable as parameters to function

Viewed 39

I have written a function that gathers some data from wide to long format. I need to this this for muliple times and therefore wanted to write a function that does it. Here is my function:

longFormat <- function(df, var){

  dflong <- df %>%
    gather(key = CONDITION, value = var, contains(var))

  dflong
}

if I pass the argument 'coltype_a' like so:

newdf <- longFormat(dfwide, 'coltype_a')

then the resulting dataframe is correct in that the fuction has looked for all columns that contain 'coltype_a' in the column name amd has turned them to long format. However, I wanted the function to name the value column as 'coltype_a' but instead the columns are being named as 'var'. Does anyone know how to get dplyr to take the argument that I give to the function LongFormat and assign it to value in the gather function?

Many thanks!

1 Answers

We could just use !!

longFormat <- function(df, var){

  dflong <- df %>%
    gather(key = CONDITION, value = !!var, contains(var))

  dflong
}

-testing

head(longFormat(iris, 'Species'))
   Sepal.Length Sepal.Width Petal.Length Petal.Width CONDITION Species
1          5.1         3.5          1.4         0.2   Species  setosa
2          4.9         3.0          1.4         0.2   Species  setosa
3          4.7         3.2          1.3         0.2   Species  setosa
4          4.6         3.1          1.5         0.2   Species  setosa
5          5.0         3.6          1.4         0.2   Species  setosa
6          5.4         3.9          1.7         0.4   Species  setosa
Related