dplyr中带条件的递归函数
首先是一个样本数据dplyr中带条件的递归函数,r,dplyr,purrr,R,Dplyr,Purrr,首先是一个样本数据 set.seed(123) dat <- tibble(x = sample(-10:10, size = 11,replace = T)) # A tibble: 11 x 1 x <int> 1 -4 2 6 3 -2 4 8 5 9
set.seed(123)
dat <- tibble(x = sample(-10:10, size = 11,replace = T))
# A tibble: 11 x 1
x
<int>
1 -4
2 6
3 -2
4 8
5 9
6 -10
7 1
8 8
9 1
10 -1
11 10
然而,我想要施加的条件是,在给定的时间步长内,y不能大于10或为负。如果y>10,则为10,如果y<0,则为0。因此,实际
y(如下y1所示)应为:
# A tibble: 11 x 2
x y y1
<int> <dbl>
1 -4 -2 0 (-2 converted to 0)
2 6 4 6
3 -2 2 4
4 8 10 10 (12 converted to 10)
5 9 19 10 (19 converted to 10)
6 -10 9 0
7 1 10 1
8 8 18 9
9 1 19 10
10 -1 18 9
11 10 28 10 (19 converte to 10)
#一个tible:11 x 2
x y y1
1-4-20(-2转换为0)
2 6 4 6
3 -2 2 4
4 8 10 10(12转换为10)
591910(19转换为10)
6 -10 9 0
7 1 10 1
8 8 18 9
9 1 19 10
10 -1 18 9
11 10 28 10(19转换为10)
您只需重新定义用于累积的函数即可:
library(tidyverse)
set.seed(123)
dat <- tibble(x = sample(-10:10, size = 11,replace = T))
fn <- function(x, y) pmax(pmin(x + y, 10), 0)
dat %>%
mutate(y = accumulate(x, fn, .init = 2)[-1])
dat
# A tibble: 11 × 2
x y
<int> <dbl>
1 -4 0
2 6 6
3 -2 4
4 8 10
5 9 10
6 -10 0
7 1 1
8 8 9
9 1 10
10 -1 9
11 10 10
库(tidyverse)
种子集(123)
达特kgolyaev以一种非常相似的方式击败了我几分钟
dat %>% mutate(y = accumulate(x, ~min(max(.x + .y, 0), 10), .init = 2)[-1])
非常感谢你。尽管如此,它还是清晰简洁。当accumulate使用几乎相同的.x
和y
作为参数时,您已将列命名为x
和y
。这是一个非常令人困惑的例子。
dat %>% mutate(y = accumulate(x, ~min(max(.x + .y, 0), 10), .init = 2)[-1])