r - 如何对 mutate_each (和 summarise_each)使用匿名函数?

标签 r dplyr anonymous-function

众所周知,可以调用 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)
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
> 

但是,如果我将函数分配给工作区,那么一切都会按预期工作:

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

   > 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

有没有办法在mutate_each的调用中动态定义函数或summarise_each

最佳答案

我们可以用括号包裹函数调用

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

关于r - 如何对 mutate_each (和 summarise_each)使用匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39613767/

相关文章:

python - 如何使用 rpy2 显示在 python 中创建的热图?

r - R 中的棘手循环?

R dplyr 不同函数不能使用 .keep_all = TRUE

r - dplyr:通过迭代向量根据某些条件填充列

erlang - 匿名函数和模式匹配

带有 getURL 和 RCurl 错误的 R API 连接(Localytics)

r - 必须加速逐行操作

javascript - JavaScript 中的代码顺序

r - {reactlog} 生成的 r Shiny react 日志图形中的 "Theme Counter"是什么?

javascript - $.proxy, bind, call, apply 的区别