【问题标题】:Multiplying elements of a column in skipping an element after each iteration在每次迭代后跳过一个元素时乘以列的元素
【发布时间】:2018-12-12 07:00:02
【问题描述】:

我在 R 中有一个数据框,其中有一列,如下所示,我想创建一个新的一列数据框,其中包含现有列元素的乘积。

Column   result
2        2*3*4*5*8*6
3        3*4*5*8*6
4        4*5*8*6 
5        5*8*6
8        8*6
6        6

【问题讨论】:

  • 您好,如果对您有用,请考虑通过单击投票按钮旁边的复选标记来接受答案。您还可以阅读更多关于它的信息here

标签: r


【解决方案1】:

我们可以使用revcumprod

df$y <- rev(cumprod(rev(df$x)))
df

#  x    y
#1 2 5760
#2 3 2880
#3 4  960
#4 5  240
#5 8   48
#6 6    6

数据

df <- data.frame(x = c(2,3,4,5,8,6))  

【讨论】:

    【解决方案2】:

    您还可以将基本 R Reduceaccumulate = TRUE 一起使用,即

    rev(Reduce(`*`, rev(df$x), accumulate = TRUE))
    #[1] 5760 2880  960  240   48    6
    

    【讨论】:

      【解决方案3】:

      我们可以使用accumulate

      library(tidyverse)
      df %>%
         mutate(y = accumulate_right(x, `*`))
      #  x    y
      #1 2 5760
      #2 3 2880
      #3 4  960
      #4 5  240
      #5 8   48
      #6 6    6
      

      数据

      df <- data.frame(x = c(2,3,4,5,8,6))   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-01
        • 2023-01-11
        • 2014-03-12
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 2011-08-15
        • 2015-07-26
        相关资源
        最近更新 更多