Dplyr多重滞后整齐吗?

时间:2019-02-16 05:09:22

标签: r dplyr lag tidyeval standard-evaluation

我试图使用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

但是,您会注意到最后一行没有使用整洁的eval,而是求助于SE。有关funs_命令的软件包信息说,由于整洁的评估,它是多余的。因此,我想知道是否可以通过整齐的评估来做到这一点?任何帮助表示赞赏,我是评估类型的新手。

2 个答案:

答案 0 :(得分:1)

来自此博客文章:multiple lags with tidy evaluation,作者:RomainFrançois

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

reprex package(v0.2.1.9000)于2019-02-15创建

答案 1 :(得分:1)

以@Tung的答案为灵感,我试图制作更通用的函数,看上去更像是tidyr函数,而不是dplyr函数,即mutate。

# lags function
lags <- function(data, var, nlags) {
  var <- enquos(var)

  data %>% 
    bind_cols(
      map_dfc(seq_len(n), 
              function(x) {
                new_var <- sprintf("L_%02d.%s", x, "y")
                data %>% transmute(new_var := lag(!!!var, x))
                }
                ))
}

# Apply function to data frame
a <- as_tibble(c(1:100))

a %>% 
  lags(value, 3)