相关疑难解决方法(0)

当库函数使用非标准求值时,重构R代码

我有一些看起来像这样的R代码:

library(dplyr)
library(datasets)

iris %.% group_by(Species) %.% filter(rank(Petal.Length, ties.method = 'random')<=2) %.% ungroup()
Run Code Online (Sandbox Code Playgroud)

赠送:

Source: local data frame [6 x 5]

  Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1          4.3         3.0          1.1         0.1     setosa
2          4.6         3.6          1.0         0.2     setosa
3          5.0         2.3          3.3         1.0 versicolor
4          5.1         2.5          3.0         1.1 versicolor
5          4.9         2.5          4.5         1.7  virginica
6          6.0         3.0          4.8         1.8  virginica
Run Code Online (Sandbox Code Playgroud)

这种按物种分组,每组只保留最短的Petal.Length.我的代码中有一些重复,因为我对不同的列和数字执行了几次.例如:

iris %.% group_by(Species) %.% filter(rank(Petal.Length, ties.method = 'random')<=2) %.% ungroup()
iris %.% group_by(Species) %.% filter(rank(-Petal.Length, ties.method = …
Run Code Online (Sandbox Code Playgroud)

r dplyr

5
推荐指数
1
解决办法
870
查看次数

如何在R中的函数内使用dplyr/magrittr的管道?

我正在尝试编写一个函数,它将数据帧和函数的名称作为参数.当我尝试写与标准的R语法功能,我可以使用取得了良好的效果eval,并substitute在建议报告由@hadley http://adv-r.had.co.nz/Computing-on-the-language.html

> df <- data.frame(y = 1:10)
> f <- function(data, x) {
+   out <- mean(eval(expr = substitute(x), envir = data))
+   return(out)
+ }
> f(data = df, x = y)
[1] 5.5
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试使用%>%运算符编写相同的函数时,它不起作用:

> df <- data.frame(y = 1:10)
> f <- function(data, x) {
+   data %>% 
+     eval(expr = substitute(x), envir = .) %>% 
+     mean()
+ }
> f(data = df, x = y)
Show Traceback
Rerun …
Run Code Online (Sandbox Code Playgroud)

r dplyr magrittr nse

4
推荐指数
2
解决办法
2509
查看次数

标签 统计

dplyr ×2

r ×2

magrittr ×1

nse ×1