在mutate中使用引号:mutate _(。dots = ...)的替代方法 [英] Using quotations inside mutate: an alternative to mutate_(.dots = ...)

查看:80
本文介绍了在mutate中使用引号:mutate _(。dots = ...)的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将不同的功能应用于小标题中的同一列。这些功能存储在字符串中。我曾经使用 mutate _ .dots 这样的参数来做到这一点:

I want to apply different functions to the same column in a tibble. These functions are stored in a character string. I used to do this with mutate_ and the .dots argument like this:

library(dplyr)

myfuns <- c(f1 = "a^2", f2 = "exp(a)", f3 = "sqrt(a)")
tibble(a = 1:3) %>% 
  mutate_(.dots = myfuns)

此方法仍然可以正常工作,但已弃用 mutate _ 。我试图通过 mutate rlang 包实现相同的结果,但并没有走得太远。

This approach still works fine but mutate_ is deprecated. I tried to achieve the same result with mutate and the rlang package but did not get very far.

在我的真实示例中, myfuns 包含大约200个函数,因此不能一一键入。

In my real example myfuns contains about 200 functions so typing them one by one is not an option.

预先感谢。

推荐答案

将字符串转换为表达式

myexprs <- purrr::map( myfuns, rlang::parse_expr )

然后使用mutate 。 r-lib.org/reference/quasiquotation.html rel = nofollow noreferrer>准报价:

then pass those expressions to regular mutate using quasiquotation:

tibble(a = 1:3) %>% mutate( !!!myexprs )
# # A tibble: 3 x 4
#       a    f1    f2    f3
#   <int> <dbl> <dbl> <dbl>
# 1     1     1  2.72  1   
# 2     2     4  7.39  1.41
# 3     3     9 20.1   1.73

请注意,这也适用于涉及多列的字符串/表达式。

Note that this will also work with strings / expressions involving multiple columns.

这篇关于在mutate中使用引号:mutate _(。dots = ...)的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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