假设我有以下专栏
**CurrentStatus**
Current
NoChange
NoChange
NoChange
NoChange
Late
Run Code Online (Sandbox Code Playgroud)
我想改变它,以便如果值为"NoChange",则使用先前值.
我试过了:
myDF %>% mutate(CurrentStatus = ifelse(CurrentStatus == "NoChange", lag(CurrentStatus), CurrentStatus)
Run Code Online (Sandbox Code Playgroud)
这似乎不起作用 - 我认为这是因为它进行了矢量化计算,因此它同时查看所有滞后.我需要它"向前滚动".我想知道在没有for循环的情况下,最有效的方法是什么.我特别想避免使用for循环,因为有些分组变量没有显示我需要注意.
谢谢!
我们可以将'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
Run Code Online (Sandbox Code Playgroud)
或者另一种选择na.locf来自zoo
library(zoo)
myDF$CurrentStatus <- with(myDF, na.locf(replace(CurrentStatus,
CurrentStatus == "NoChange", NA)))
Run Code Online (Sandbox Code Playgroud)