如何使用匿名函数mutate_each(和summarise_each)? [英] How to use anonymous functions for mutate_each (and summarise_each)?

查看:623
本文介绍了如何使用匿名函数mutate_each(和summarise_each)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,可以在R中调用函数,而不将它们分配给环境,例如

 > (function(x){x / 2})(5)
[1] 2.5

我想使用这些函数,在一个 mutate_each (或 summarise_each )调用中。例如,使用



df< - data.frame(a = runif(10),b = rnorm(10))



我可能会尝试执行以下操作之一,但都返回错误:

  library(dplyr)

> df%>%
+ mutate_each(funs((function(x){x / 2})),a,b)
eval(substitute(expr),envir, b $ b列a不支持类型CLOSXP
>
> df%>%
+ mutate_each(list((function(x){x / 2})),a,b)
错误:is.fun_list(call)不为TRUE
>
>
> df%>%
+ mutate_each(funs((function(x){x / 2})(。)),a,b)
vapply错误(dots [missing_names],function )make_name(x $ expr),character(1)):
值必须是长度1,
但是FUN(X [[1]])的结果是长度2
>

但是,如果我将功能分配给工作区,那么所有的工作原理如下:

  tmp_fn<  -  function(x){x / 2} 

 > df%>%
+ mutate_each(funs(tmp_fn),a,b)
ab
1 0.360048105 -0.452285314
2 0.020175136 0.253063103
3 0.002351454 -0.148997643
4 0.262808493 -0.599555244
5 0.057246370 0.007567076
6 0.400027700 0.264901865
7 0.120505411 -0.346171709
8 0.266166200 0.116066231
9 0.031302148 -0.129739601
10 0.250212897 0.230194217

有没有办法在调用$ code动态定义函数mutate_each summarise_each

解决方案

使用括号的函数调用

  df%>%
mutate_each(funs(((function(x){x / 2})(。))))


As we know, it is possible to call functions in R without assigning them to the environment, e.g.

> (function(x){x/2})(5)
[1] 2.5

I would like to use functions like these, on the fly, in a mutate_each (or summarise_each) call. For example, with

df <- data.frame(a = runif(10), b = rnorm(10))

I might attempt to do one of the following, but they all return errors:

library(dplyr)

> df %>%
+     mutate_each(funs((function(x){x/2})), a, b)
Error in eval(substitute(expr), envir, enclos) : 
  Unsupported type CLOSXP for column "a"
> 
> df %>%
+     mutate_each(list((function(x){x/2})), a, b)
Error: is.fun_list(calls) is not TRUE
> 
> 
> df %>%
+     mutate_each(funs((function(x){x/2})(.)), a, b)
Error in vapply(dots[missing_names], function(x) make_name(x$expr), character(1)) : 
  values must be length 1,
 but FUN(X[[1]]) result is length 2
> 

However, if I assign the function to the workspace, then all works as expected:

tmp_fn <- function(x){x/2}

and

   > df %>%
+     mutate_each(funs(tmp_fn), a, b)
             a            b
1  0.360048105 -0.452285314
2  0.020175136  0.253063103
3  0.002351454 -0.148997643
4  0.262808493 -0.599555244
5  0.057246370  0.007567076
6  0.400027700  0.264901865
7  0.120505411 -0.346171709
8  0.266166200  0.116066231
9  0.031302148 -0.129739601
10 0.250212897  0.230194217

Is there a way to dynamically define functions in the call to mutate_each or summarise_each?

解决方案

We can wrap the function call with parentheses

df %>%
     mutate_each(funs(((function(x){x/2})(.))))

这篇关于如何使用匿名函数mutate_each(和summarise_each)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆