Carry value forward in dplyr chain

前端 未结 2 601
梦谈多话
梦谈多话 2020-12-21 08:54

Suppose I have the following column

**CurrentStatus**
Current
NoChange
NoChange
NoChange
NoChange
Late

I want to mutate it so that if the v

相关标签:
2条回答
  • 2020-12-21 09:14

    We can replace the 'NoChange' to NA and then use fill

    library(tidyverse)
    myDF %>%
        mutate(CurrentStatus = replace(CurrentStatus, CurrentStatus == "NoChange", NA)) %>%
        fill(CurrentStatus)
    #  CurrentStatus
    #1       Current
    #2       Current
    #3       Current
    #4       Current
    #5       Current
    #6          Late
    

    Or another option is na.locf from zoo

    library(zoo)
    myDF$CurrentStatus <-  with(myDF, na.locf(replace(CurrentStatus, 
                  CurrentStatus == "NoChange", NA)))
    
    0 讨论(0)
  • 2020-12-21 09:16

    You could use something like this:

    rfwd<-function(value,trigger)
    {
      c("",value)[cummax(seq_along(value)*(trigger))+1]
    }
    

    and your answer would be rfwd(CurrentStatus,CurrentStatus!="NoChange")

    > rfwd(LETTERS,seq_along(LETTERS)%%10==0)
     [1] ""  ""  ""  ""  ""  ""  ""  ""  ""  "J" "J" "J" "J" "J" "J" "J" "J" "J" "J" "T" "T" "T" "T" "T" "T" "T"
    
    
    0 讨论(0)
提交回复
热议问题