I have a dataframe with 3 columns, but the 3rd column has some missing values which need to be filled in with the following logic.
The desired result is that there are n
This is essentially a "last observation carried forward" task
library(zoo)
levels(df$part)[1] <- NA
df$part <- with(df,
ave(part, item, FUN=function(x) {
x <- na.locf(x,na.rm=FALSE)
x[is.na(x)] <- na.omit(x)[1]
x
})
)
# item week part
#1 A 1 X
#2 A 2 X
#3 A 3 X
#4 A 4 X
#5 A 5 Y
#6 A 6 Y
#7 A 7 Y
#8 B 1 Z
#9 B 2 Z
#10 B 3 Z
#11 D 10 T
#12 D 11 T
#13 D 12 U
#14 D 13 U
#15 D 14 U
all.equal(df,df2, check.names=FALSE)
#[1] TRUE