Suppose that you would like to create a function which does a series of computations on a data frame. You would like to pass a column as this function’s argument. Something like:
data(cars)
convertToKmh <- function(dataset, col_name){
dataset$col_name <- dataset$speed * 1.609344
return(dataset)
}
This example is obviously not very interesting (you don’t need a function for this), but it will illustrate the point. You would like to append a column called speed_in_kmh
with the speed in kilometers per hour to this dataset, but this is what happens:
head(convertToKmh(cars, "speed_in_kmh"))
## speed dist col_name
## 1 4 2 6.437376
## 2 4 10 6.437376
## 3 7 4 11.265408
## 4 7 22 11.265408
## 5 8 16 12.874752
## 6 9 10 14.484096
Your column is not called speed_in_kmh
but col_name
! It turns out that there is a very simple solution:
convertToKmh <- function(dataset, col_name){
dataset[col_name] <- dataset$speed * 1.609344
return(dataset)
}
head(convertToKmh(cars, "speed_in_kmh"))
## speed dist speed_in_kmh
## 1 4 2 6.437376
## 2 4 10 6.437376
## 3 7 4 11.265408
## 4 7 22 11.265408
## 5 8 16 12.874752
## 6 9 10 14.484096
You can access columns with []
instead of $
.
But sometimes you want to do more complex things and for example have a function that groups by a variable and then computes new variables, filters by another and so on. You would like to avoid having to hard code these variables in your function, because then why write a function and of course you would like to use dplyr
to do it.
I often use dplyr
functions in my functions. For illustration purposes, consider this very simple function:
simpleFunction <- function(dataset, col_name){
require("dplyr")
dataset %>%
group_by(col_name) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}
simpleFunction(cars, "dist")
This function takes a dataset as an argument, as well as a column name. However, this does not work. You get this error:
Error: unknown variable to group by : col_name
The variable col_name
is passed to simpleFunction()
as a string, but group_by()
requires a variable name. So why not try to convert col_name
to a name?
simpleFunction <- function(dataset, col_name){
require("dplyr")
col_name <- as.name(col_name)
dataset %>%
group_by(col_name) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}
simpleFunction(cars, "dist")
You get the same error as before:
Error: unknown variable to group by : col_name
So how can you pass a column name to group_by()
? Well, there is another version of group_by()
called group_by_()
that uses standard evaluation. You can learn more about it here. Let’s take a look at what happens when we use group_by_()
:
simpleFunction <- function(dataset, col_name){
require("dplyr")
dataset %>%
group_by_(col_name) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}
simpleFunction(cars, "dist")
## # A tibble: 35 x 2
## dist mean_speed
## <dbl> <dbl>
## 1 2 4.0
## 2 4 7.0
## 3 10 6.5
## 4 14 12.0
## 5 16 8.0
## 6 17 11.0
## 7 18 10.0
## 8 20 13.5
## 9 22 7.0
## 10 24 12.0
## # ... with 25 more rows
We can even use a formula instead of a string:
simpleFunction(cars, ~dist)
## # A tibble: 35 x 2
## dist mean_speed
## <dbl> <dbl>
## 1 2 4.0
## 2 4 7.0
## 3 10 6.5
## 4 14 12.0
## 5 16 8.0
## 6 17 11.0
## 7 18 10.0
## 8 20 13.5
## 9 22 7.0
## 10 24 12.0
## # ... with 25 more rows
What if you want to pass column names and constants, for example to filter without hardcoding anything?
Trying to do it naively will only yield pain and despair:
simpleFunction <- function(dataset, col_name, value){
require("dplyr")
dataset %>%
filter_(col_name == value) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}
> simpleFunction(cars, "dist", 10)
mean_speed
1 NaN
> simpleFunction(cars, dist, 10)
Error in col_name == value :
comparison (1) is possible only for atomic and list types
> simpleFunction(cars, ~dist, 10)
mean_speed
1 NaN
To solve this issue, we need to know a little bit about two concepts,lazy evaluation and non-standard evaluation. I recommend you read the following document from Hadley Wickham’s bookAdvanced R as well as the part on lazy evaluation here.
A nice package called lazyeval
can help us out. We would like to make R understand that the column name is not col_name
but the string inside it "dist"
, and now we would like to use filter()
fordist
equal to 10
.
In the lazyeval
package, you’ll find the function interp()
.interp()
allows you to
build an expression up from a mixture of constants and variables.
Take a look at this example:
library(lazyeval)
interp(~x+y, x = 2)
## ~2 + y
What you get back is this nice formula that you can then use within functions. To see why this is useful, let’s look at the above example again, and make it work using interp()
:
simpleFunction <- function(dataset, col_name, value){
require("dplyr")
require("lazyeval")
filter_criteria <- interp(~y == x, .values=list(y = as.name(col_name), x = value))
dataset %>%
filter_(filter_criteria) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}
simpleFunction(cars, "dist", 10)
## mean_speed
## 1 6.5
And now it works! For some reason, you have to pass the column name as a string though.
Sources: apart from the documents above, the following stackoverflow threads helped me out quite a lot: In R: pass column name as argument and use it in function with dplyr::mutate() and lazyeval::interp() and Non-standard evaluation (NSE) in dplyr’s filter_ & pulling data from MySQL.