假设我有以下列
**CurrentStatus**
Current
NoChange
NoChange
NoChange
NoChange
Late
我想改变它,以便如果该值为“NoChange”,则它使用先前的值。
I tried:
myDF %>% mutate(CurrentStatus = ifelse(CurrentStatus == "NoChange", lag(CurrentStatus), CurrentStatus)
这似乎不起作用——我认为这是因为它进行了矢量化计算,因此它会同时查看所有滞后。我需要它“向前滚动”。我想知道在没有 for 循环的情况下最有效的方法是什么。我特别想避免 for 循环,因为有一些我需要注意的分组变量没有显示。
Thanks!
我们可以将 '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
from zoo
library(zoo)
myDF$CurrentStatus <- with(myDF, na.locf(replace(CurrentStatus,
CurrentStatus == "NoChange", NA)))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)