使用 dplyr 的递归函数 [英] Recursive function using dplyr

查看:23
本文介绍了使用 dplyr 的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据:

dat <- tibble(
         day = 200:210,
         x = sample(-10:10, size = 11,replace = T))

我有一个初始值为 2 的变量 y.我想通过在给定的时间步长内将 x 添加到 y 来计算 y 的最终值以下符号:

I have a variable y with initial value of 2. I want to calculate the final value of y by adding x to y in a given time step following the following notation:

y[i] = y[i-1] + x

如果我这样做:

y <- 5
dat %>% mutate(y = y + x)

它将 y 添加到每个 x.

It adds y to each x.

# A tibble: 11 x 3
    day     x     y
  <int> <int> <dbl>
1   200     4     9
2   201     3     8
3   202    -4     1
4   203    -7    -2
5   204    -3     2
6   205     1     6
7   206    -5     0
8   207    -1     4
9   208    -4     1
10  209    -2     3
11  210     4     9

The answer should be:

  # A tibble: 11 x 3
    day     x     y
  <int> <int> <dbl>
1   200     4     9
2   201     3     12
3   202    -4     8
4   203    -7     1
5   204    -3     -2
6   205     1     -1
7   206    -5     -6
8   207    -1     -7
9   208    -4     -11
10  209    -2     -13
11  210     4     -9

如何使用 dplyr 包实现此目的?或任何其他快速且快速的方法.

How do I achive this using dplyr package? Or any other method that is quick and fast.

编辑

如果我想强加一个条件,y 不能超过 10 或为负.如果超过 10,则设为 10,如果为负,则设为零.我如何实现这一目标:

If I want to impose a condition such that y cannot exceed 10 or be negative .If it exceeds 10, make it 10 and if it is negative, make it zero. How do I achieve this:

一点点:11 x 3

      day     x     y     y1
  1   200     4     9     9
  2   201     3     12    10
  3   202    -4     8     6
  4   203    -7     1     0 
  5   204    -3     -2    0
  6   205     1     -1    0
  7   206    -5     -6    0
  8   207    -1     -7    0  
  9   208    -4     -11   0
  10  209    -2     -13   0
  11  210     4     -9    0

推荐答案

我们可以使用 purrr 中的 accumulate.使用 accumulate,对 'x' 元素进行递归 sum,同时以 5 (.init = 5) 的值初始化并删除第一个accumulate 输出的元素 ([-1])

We could use accumulate from purrr. With accumulate, do the recursive sum of 'x' elements while initiating with a value of 5 (.init = 5) and remove the first element of accumulate output ([-1])

library(purrr)
library(dplyr)
dat %>%
     mutate(y = accumulate(x, ~ .x + .y, .init = 5)[-1])
# A tibble: 11 x 3
#     day     x      y
#   <int> <int>  <dbl>
# 1   200     4   9.00
# 2   201     3  12.0 
# 3   202    -4   8.00
# 4   203    -7   1.00
# 5   204    -3 - 2.00
# 6   205     1 - 1.00
# 7   206    -5 - 6.00
# 8   207    -1 - 7.00
# 9   208    -4 -11.0 
#10   209    -2 -13.0 
#11   210     4 - 9.00

<小时>

base R 中的类似方法是

dat$y <- Reduce(function(u, v)  u + v , dat$x, init = 5, accumulate = TRUE)[-1]
dat$y
#[1]   9  12   8   1  -2  -1  -6  -7 -11 -13  -9

这篇关于使用 dplyr 的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆