我试图在 dplyr 中使用尽可能少的代码来实现多个滞后,同时坚持整洁的评估。以下标准评估 (SE) 代码有效:
#if(!require(dplyr)) install.packages("dplyr");
library(dplyr)
a=as_tibble(c(1:100))
lags=3
lag_prefix=paste0("L", 1:lags, ".y")
multi_lag=setNames(paste("lag(.,", 1:lags, ")"), lag_prefix)
a %>% mutate_at(vars(value), funs_(multi_lag)) #final line
# A tibble: 100 x 4
value L1.y L2.y L3.y
<int> <int> <int> <int>
1 1 NA NA NA
2 2 1 NA NA
3 3 2 1 NA
4 4 3 2 1
5 5 4 3 2
6 6 5 4 3
7 7 6 5 4
8 8 7 6 5
9 9 8 7 6
10 10 9 8 7
# ... with 90 more rows
但是,您会注意到最后一行没有使用 tidy eval,而是求助于 SE。有关 funs_ 命令的软件包信息表明,由于整齐的 eval,它是多余的。因此,我想知道是否可以通过整洁的评估来做到这一点?感谢任何帮助,我是评估类型的新手。
来自这篇博文:多重滞后且评估整齐 https://purrple.cat/blog/2018/03/02/multiple-lags-with-tidy-evaluation/作者:罗曼·弗朗索瓦
library(rlang)
library(tidyverse)
a <- as_tibble(c(1:100))
n_lags <- 3
lags <- function(var, n = 3) {
var <- enquo(var)
indices <- seq_len(n)
# create a list of quosures by looping over `indices`
# then give them names for `mutate` to use later
map(indices, ~ quo(lag(!!var, !!.x))) %>%
set_names(sprintf("L_%02d.%s", indices, "y"))
}
# unquote the list of quosures so that they are evaluated by `mutate`
a %>%
mutate_at(vars(value), funs(!!!lags(value, n_lags)))
#> # A tibble: 100 x 4
#> value L_01.y L_02.y L_03.y
#> <int> <int> <int> <int>
#> 1 1 NA NA NA
#> 2 2 1 NA NA
#> 3 3 2 1 NA
#> 4 4 3 2 1
#> 5 5 4 3 2
#> 6 6 5 4 3
#> 7 7 6 5 4
#> 8 8 7 6 5
#> 9 9 8 7 6
#> 10 10 9 8 7
#> # ... with 90 more rows
Created on 2019-02-15 by the reprex package https://reprex.tidyverse.org (v0.2.1.9000)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)