【问题标题】:dplyr 0.7 equivalent for deprecated mutate_dplyr 0.7 等效于弃用的 mutate_
【发布时间】:2018-01-03 17:19:45
【问题描述】:

我在 dplyr 0.7 中找不到替换将被弃用的 mutate_ 函数的方法。

mutate_ 函数在我的用例中很有用:我在数据库(字符串格式)中存储了许多指令(如果需要,可以对其进行过滤)并将这些指令应用于一个或多个数据帧。

例如:

dplyr::tibble(test = "test@test") %>% 
  dplyr::mutate_(.dots = list("test2" = "substr(test, 1, 5)",
                              "test3" = "substr(test, 5, 5)"))

有没有办法让 dplyr 0.7 保持变量和指令为字符?

【问题讨论】:

  • 文档?mutate_ 声明“dplyr 现在使用整洁的评估语义”,指的是 rlang 包,它有一个关于“整洁评估”的小插图。如果你走那条路,祝你好运。

标签: r dplyr rlang tidyeval


【解决方案1】:

这是另一种选择

a <- "test2"
b <- "test3"
dplyr::tibble(test = "test@test") %>% 
dplyr::mutate(a := !!rlang::parse_expr("substr(test, 1, 5)"),
  b := !!rlang::parse_expr("substr(test, 5, 5)"))
# # A tibble: 1 x 3
#        test     a     b
#       <chr> <chr> <chr>
# 1 test@test test@     @

我们使用:=操作符来动态命名带有字符串的参数,我们解析表达式字符串进行转换并用!!解包

【讨论】:

  • @TylerRinker 我更新为parse_expr(),它没有被弃用,也不需要指定环境,因为我们真的没有使用它。
【解决方案2】:

为了稍微扩展MrFlick 的示例,假设您有许多存储为字符串的指令,以及您想要分配给结果计算的相应名称:

ln <- list( "test2", "test3" )
lf <- list( "substr(test, 1, 5)", "substr(test, 5, 5)" )

将名称与他们的说明相匹配,并将所有内容转换为 quosures:

ll <- setNames( lf, ln ) %>% lapply( rlang::parse_quosure )

根据aosmith 的建议,现在可以使用特殊的!!! 运算符将整个列表传递给mutate:

tibble( test = "test@test" ) %>% mutate( !!! ll )
# # A tibble: 1 x 3
#        test test2 test3
#       <chr> <chr> <chr>
# 1 test@test test@     @

【讨论】:

  • 您也可以使用mutate(X, !!! ll) 而不是整个do.call 步骤。
  • 好主意,奥史密斯。我会更新答案。谢谢。
  • 非常感谢 MrFlick、Artem 和 aosmith!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 1970-01-01
  • 2016-03-09
  • 2012-06-12
  • 2021-03-02
相关资源
最近更新 更多