Data frame columns as arguments to dplyr functions

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值