我有一些看起来像这样的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语法功能,我可以使用取得了良好的效果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)