这里详细介绍了基本方法和dplyr如何使用dplyr 创建使用自己滞后值的列
我希望第一行等于k,然后每一行都是"c"加"a"减"b"的滞后。
基本方法有效。
但是dplyr方法并没有产生与基本方法相同的结果。请参阅:
library(tidyverse)
k <- 10 # Set a k value
df1 <- tribble(
~a, ~b,
1, 1,
1, 2,
1, 3,
1, 4,
1, 5,)
# Base approach
df1$c <- df1$a - df1$b
df1[1, "c"] <- k
df1$c <- cumsum(df1$c)
df1
#> # A tibble: 5 x 3
#> a b c
#> <dbl> <dbl> <dbl>
#> 1 1 1 10
#> 2 1 2 9
#> 3 1 3 7
#> 4 1 4 4
#> 5 1 5 0
# New df
df2 <- tribble(
~a, ~b,
1, 1,
1, 2,
1, 3,
1, 4,
1, 5,)
# dplyr approach
df2 %>%
mutate(c = lag(cumsum(a - b),
default = k))
#> # A tibble: 5 x 3
#> a b c
#> <dbl> <dbl> <dbl>
#> 1 1 1 10
#> 2 1 2 0
#> 3 1 3 -1
#> 4 1 4 -3
#> 5 1 5 -6
# Gives two different dataframes
由reprex包(v0.3.0(于2020-03-05创建
可选代码和所需输出:
library(tidyverse)
# Desired output
tribble(
~a, ~b, ~c,
1, 1, 10,
1, 2, 9,
1, 3, 7,
1, 4, 4,
1, 5, 0)
#> # A tibble: 5 x 3
#> a b c
#> <dbl> <dbl> <dbl>
#> 1 1 1 10
#> 2 1 2 9
#> 3 1 3 7
#> 4 1 4 4
#> 5 1 5 0
df2 <- tribble(
~a, ~b,
1, 1,
1, 2,
1, 3,
1, 4,
1, 5,)
k <- 10
df2 %>%
mutate(c = case_when(
row_number() == 1 ~ k,
row_number() != 1 ~ lag(c) + a - b))
#> Error in x[seq_len(xlen - n)]: object of type 'builtin' is not subsettable
由reprex包(v0.3.0(于2020-03-05创建
是否有另一种提供基本方法输出的tidyverse方法?
我们可以做:
library(dplyr)
df2 %>% mutate(c = k + cumsum(a-b))
# A tibble: 5 x 3
# a b c
# <dbl> <dbl> <dbl>
#1 1 1 10
#2 1 2 9
#3 1 3 7
#4 1 4 4
#5 1 5 0
当a - b
的第一个值不等于0时,我们可以使用:
df2 %>% mutate(c = c(k, k + cumsum(a-b)[-1]))