【发布时间】:2018-02-15 13:17:53
【问题描述】:
我正在尝试学习如何使用rlang 在 R 中编写特定领域的语言。这只是一个了解解析和操作如何工作的小例子。
假设我有以下数据:
> top <- seq(2,10,2)
> bottom <- rep(2,length(top))
> times <- rep(10,length(top))
> df <- tibble::tibble(top,bottom,times)
> df
top bottom times
<dbl> <dbl> <dbl>
1 2.00 2.00 10.0
2 4.00 2.00 10.0
3 6.00 2.00 10.0
4 8.00 2.00 10.0
5 10.0 2.00 10.0
我想要一种采用以下示例的领域特定语言
1.
df_result1 <- divi(top | bottom ~ times, df)
2.
df_result2 <- divi(top | bottom ~ 1, df)
并产生以下内容:
1.
> df_result1
# A tibble: 5 x 4
top bottom times result
<dbl> <dbl> <dbl> <dbl>
1 2.00 2.00 10.0 10.0
2 4.00 2.00 10.0 20.0
3 6.00 2.00 10.0 30.0
4 8.00 2.00 10.0 40.0
5 10.0 2.00 10.0 50.0
2.
> df_result2
# A tibble: 1 x 1
result
<dbl>
1 3.00
在dplyr 行话中,函数是:
1.
df_result1 <- df %>% mutate(result = (top/bottom)*times)
2.
df_result2 <- df %>% summarise(result = mean((top/bottom)))
更新
经过一些特别的工作,我为其中一个案例提出了以下建议。它在技术上可能很丑陋,但它可以完成工作。
divi <- function(form, data){
data %>% mutate(result=eval_tidy(f_lhs(f_lhs(form)))/
eval_tidy(f_rhs(f_lhs(form)))*
eval_tidy(f_rhs(form)))
}
divi(top | bottom ~ times, df)
top bottom times ressult
<dbl> <dbl> <dbl> <dbl>
1 2 2 10 10
2 4 2 10 20
3 6 2 10 30
4 8 2 10 40
5 10 2 10 50
【问题讨论】: