【问题标题】:Creating a new column using the previous value of a different column and the previous value of itself使用不同列的先前值和自身的先前值创建新列
【发布时间】:2020-04-27 15:27:26
【问题描述】:

如何创建一个起始值为 1 的新列,以下值是列的前一个值 (b) 与其自身的前一个值 (d) 的乘积?

这些数据只是组成,但有我的数据的结构:

> a <- rep(1:10, 3)
> b <- runif(30)
> c <- tibble(a,b)
> c
# A tibble: 30 x 2
       a     b
   <int> <dbl>
 1     1 0.945
 2     2 0.280
 3     3 0.464
 4     4 0.245
 5     5 0.917
 6     6 0.913
 7     7 0.144
 8     8 0.481
 9     9 0.873
10    10 0.754
# ... with 20 more rows

然后我尝试计算d列:

> c <- c %>%
+   group_by(a) %>%
+   mutate(d = accumulate(lag(b, k = 1), `*`, .init = 1))

它应该看起来像这样

# A tibble: 30 x 3
# Groups:   a [10]
       a     b      d
   <int> <dbl>  <dbl>
 1     1 0.945  1    <--- b[1] * d[1] = d[2]
 2     2 0.280  0.945
 3     3 0.464  0.265
 4     4 0.245  0.123
 5     5 0.917  0.03 
#...

但我却收到此错误消息。

Fehler: Column `d` must be length 3 (the group size) or one, not 4

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    问题在于,当您使用 .init = 初始化 accumulate 时,会添加一个额外的向量的第一个元素。

    你可以试试这个:

    library(dplyr)
    library(purrr)
    
     c %>%
       group_by(a) %>%
       mutate(d = accumulate(b[(2:length(b))-1], `*`,.init=1)) %>% 
       arrange(a)
    #       a     b      d
    #   <int> <dbl>  <dbl>
    # 1     1 0.266 1     
    # 2     1 0.206 0.266 
    # 3     1 0.935 0.0547
    # 4     2 0.372 1     
    # 5     2 0.177 0.372 
    # … with 25 more rows
    

    数据

    library(tibble)
    set.seed(1)
     a <- rep(1:10, 3)
     b <- runif(30)
     c <- tibble(a,b)
    

    【讨论】:

    • 您好伊恩,非常感谢您的解决方案!将 -1 添加到 mutate(d = accumulate(b[2:length(b)-1], `*`, .init = 1)) 就可以了!非常感谢
    • 很高兴它对你有用。我编辑了我的答案以产生您正在寻找的结果。
    【解决方案2】:

    使用dplyr,我会这样做:

    c %>% 
      mutate(d = 1*accumulate(.x = b[-length(b)], 
                             .init = 1,
                             .f = `*`))
    
    # # A tibble: 30 x 3
    # a      b        d
    # <int>  <dbl>    <dbl>
    #   1     1 0.562  1       
    # 2     2 0.668  0.562   
    # 3     3 0.100  0.375   
    # 4     4 0.242  0.0376  
    # 5     5 0.0646 0.00907 
    # 6     6 0.373  0.000586
    # 7     7 0.664  0.000219
    # 8     8 0.915  0.000145
    # 9     9 0.848  0.000133
    # 10    10 0.952  0.000113
    # # ... with 20 more rows
    

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多