将匿名函数与summary_each或mutate_each一起使用 [英] Using anonymous functions with summarize_each or mutate_each

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

问题描述

我想在对 summarize_each 的调用中使用匿名函数:

I want to use anonymous functions in calls to summarize_each:

# how to use an anonymous function in dplyr
df_foo = data_frame(x = rnorm(100),
                    y = rnorm(100))

df_foo %>% 
  summarize_each(funs(function(bar) sum(bar/10)))

我将如何去实现这个目标?显然,在使用该功能之前先对其命名。

How would I go about achieving this? Obviously, naming the function before using it works.

推荐答案

要解决的问题是使用大量的括号,以便对所有内容进行评估:

It's a matter of using a lot of parentheses so everything gets evaluated:

df_foo %>% 
  summarize_each(funs(((function(bar){sum(bar/10)})(.))))
#
# Source: local data frame [1 x 2]
# 
#          x          y
#      (dbl)      (dbl)
# 1 1.113599 -0.4766853

您需要的地方


  • 用括号括住函数定义,以便对其进行定义

  • 一组带有的括号。告诉 funs 保留传递给它的数据的参数(对于单参数函数似乎是多余的,但对于多参数函数则不是;请参见?funs (更多示例),并且

  • 将整个事物括起来以对其进行实际评估,

  • parentheses around the function definition so it gets defined,
  • a set of parentheses with a . to tell funs which parameter to stick the data passed to it in (seemingly redundant with single-parameter functions, but not so with multi-parameter ones; see ?funs for more examples), and
  • parentheses around the whole thing to actually evaluate it,

有点荒谬,但这似乎是枪支可以处理的最简洁的方法。如果您查看自己必须编写的内容以评估类似的匿名函数,那么这很有道理,例如

which is kind of ridiculous, but that seems to be the most concise funs can handle. It makes some sense if you look at what you'd have to write to evaluate a similar anonymous function on its own line, e.g.

(function(bar){sum(bar/10)})(df_foo$x)

不过包裹整个东西的那对对于 funs 是额外的。如果愿意,可以对大括号使用 {} 代替括号,这可能在语法上更有意义。

though the pair wrapping the whole thing are extra for funs. You can use braces {} instead for the outer pair if you prefer, which might make more syntactic sense.

这篇关于将匿名函数与summary_each或mutate_each一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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