![](/img/trans.png)
[英]In the dplyr package can you mutate a column based on the values in a different column
[英]Mutate a new column based on lagged values within that column - dplyr approach
此處詳細介紹了基本方法和 dplyr How to create a column which using its own Lag value using 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 年 3 月 5 日創建
替代代碼和所需的輸出:
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 年 3 月 5 日創建
是否有另一種 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]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.