在dplyr链中携带价值

时间:2017-08-07 08:25:36

标签: r dplyr

假设我有以下专栏

**CurrentStatus**
Current
NoChange
NoChange
NoChange
NoChange
Late

我想改变它,以便如果值为" NoChange"它使用先前的值。

我试过了:

myDF %>% mutate(CurrentStatus = ifelse(CurrentStatus == "NoChange", lag(CurrentStatus), CurrentStatus)

这似乎不起作用 - 我认为这是因为它进行了矢量化计算,因此它同时查看了所有滞后。我需要它来推进"前进"。我想知道在没有for循环的情况下,最有效的方法是什么。我特别想避免使用for循环,因为有些分组变量没有显示我需要注意。

谢谢!

2 个答案:

答案 0 :(得分:7)

我们可以将“NoChange”替换为NA,然后使用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

或其他选项na.locf来自zoo

library(zoo)
myDF$CurrentStatus <-  with(myDF, na.locf(replace(CurrentStatus, 
              CurrentStatus == "NoChange", NA)))

答案 1 :(得分:0)

您可以使用以下内容:

undefined: auth go

,您的答案将是rfwd<-function(value,trigger) { c("",value)[cummax(seq_along(value)*(trigger))+1] }

rfwd(CurrentStatus,CurrentStatus!="NoChange")