【问题标题】:R Using previous iteration result in next iterationR使用上一次迭代导致下一次迭代
【发布时间】:2014-06-30 01:14:06
【问题描述】:

我有一个包含两列的数据框:

id  score  
1     0.5  
1     0.7  
1     0.8  
2     0.7  
2     0.8  
2     0.9  

我想通过迭代“score”的行,应用两个函数之一(“function1”或“function2”)来生成一个新列(“new”),条件是“id”是不同的还是与最后一行 id 值相同。这部分我可以做,我的问题是我想让function2引用function1生成的值。比如:

function1 <- function(score) {new <- score*10 return(new)}
function2 <- function(score) {new <- score*new[-1] return(new)}

id  score  new    
1     0.5  5   
1     0.7  3.5  
1     0.8  2.8  
2     0.7  7  
2     0.8  5.6  
2     0.9  5.04  

我知道 apply() 不能做这种向后引用,但我一辈子都想不出如何用循环来做。任何建议都会很棒,因为我现在正在拔头发!

【问题讨论】:

    标签: r loops dynamic recursion apply


    【解决方案1】:

    对于问题中的具体例子:

    DT <- read.table(text="id  score  
    1     0.5  
    1     0.7  
    1     0.8  
    2     0.7  
    2     0.8  
    2     0.9  ", header=TRUE)
    
    library(data.table)
    setDT(DT)
    
    DT[, new := 10*cumprod(score), by=id]
    #   id score  new
    #1:  1   0.5 5.00
    #2:  1   0.7 3.50
    #3:  1   0.8 2.80
    #4:  2   0.7 7.00
    #5:  2   0.8 5.60
    #6:  2   0.9 5.04
    

    在更一般的情况下,您需要Reduce,而我使用了cumprod

    【讨论】:

      【解决方案2】:
      df <- data.frame(id=rep(c(1,2),each=3), score=c(.5,.7,.8,.7,.8,.9))
      

      这可以通过dplyr 包中的mutate() 函数相对简单地完成:

      require(dplyr)    
      mutate(group_by(df, id), new = 10*cumprod(score))
      
      #Source: local data frame [6 x 3]
      #Groups: id
      
      #  id score  new
      #1  1   0.5 5.00
      #2  1   0.7 3.50
      #3  1   0.8 2.80
      #4  2   0.7 7.00
      #5  2   0.8 5.60
      #6  2   0.9 5.04
      

      【讨论】:

        猜你喜欢
        • 2018-06-21
        • 1970-01-01
        • 1970-01-01
        • 2021-10-05
        • 2016-04-13
        • 1970-01-01
        • 2015-11-11
        • 2021-05-22
        相关资源
        最近更新 更多