Data frame columns as arguments to dplyr functions
来源:互联网 发布:mac 定时关闭程序 编辑:程序博客网 时间:2024/05/16 08:36
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_speed1 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_speed1 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.
- Data frame columns as arguments to dplyr functions
- Tips: wxString as functions returning and const wxString& as functions arguments
- How to Get the Frequency Table of a Categorical Variable as a Data Frame in R
- Introduction to dplyr
- as.data.frame一定要小心的一个参数stringsAsFactors
- as.data.frame一定要小心的一个参数stringsAsFactors
- R语言dplyr包介绍 introduction to dplyr
- [JavaScript]Functions as Methods
- R-list-to-data-frame列表转数据框
- Join and set operations come to dplyr
- Oracle 10g Enhancements to Analytical Functions -- Using Partitioned Outer Joins To "Densify" Data
- How to do take snapshot image as binary data?
- How To Export MySQL Data as Insert Statements
- [JavaScript] Defining and invoking functions, Function Arguments
- [JavaScript] Nested Functions as Closures
- Converting Oracle rows to columns
- Cut Frame From Decoding Stream To Show As a RGB Form Picture
- data.frame操作
- ubuntu 进不去界面解决方案
- Servlet中的过滤器Filter详解
- 开发日记——手机安全卫士 Day06 2016-7-25 修改部分界面,增加了联系人搜索功能,完成部分黑名单功能
- 算法:枚举(穷举)法
- Maximum Depth of Binary Tree
- Data frame columns as arguments to dplyr functions
- word 的使用(七) —— 绘图工具
- AutoCompleteTextView和MultiAutoCompleteTextView
- system.sys 与 system.err 打印的区别异同
- 各种细的知识点(一)
- 手机端QQ登录openid与网站端QQ登录openid不一样
- CentOS7修改yum阿里源
- 判断一个序列是否为另一个栈的出栈序列(栈的压入、弹出序列)
- Ubuntu 14.04安装TeamViewer