在dplyr链中传递值

5
假设我有以下列:
**CurrentStatus**
Current
NoChange
NoChange
NoChange
NoChange
Late

我希望对它进行变异,如果值为“NoChange”,则使用先前的值。

我尝试过:

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

似乎不起作用 - 我认为原因是它执行了向量化计算,因此同时查看所有滞后期。我需要将其“向前滚动”。我想知道在没有for循环的情况下最有效的方法是什么。我特别想避免使用for循环,因为有一些未显示的分组变量需要注意。

谢谢!

2个回答

9
我们可以将“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

另外一个选项是来自 zoona.locf

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

0
你可以使用类似这样的代码:
rfwd<-function(value,trigger)
{
  c("",value)[cummax(seq_along(value)*(trigger))+1]
}

你的答案将会是 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"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接