r - How do I replicate values based on previous value -
how replicate 1 value based on previous value?
e.g
my dataset
name <- c("sergio",na,na,na,na,"john", na,na,na,na,na,na) number <-c(1234,na,na,na,na,5678, na,na,na,na,na,na) mydata <- cbind(as.data.frame(name),as.data.frame(number))
new dataset
name number sergio 1234 sergio 1234 sergio 1234 sergio 1234 john 5678 john 5678 john 5678 john 5678 john 5678 john 5678 ....
etc
you can use na.locf
"zoo" package:
mydata <- data.frame( name = c("sergio",na,na,na,na,"john", na,na,na,na,na,na), number = c(1234,na,na,na,na,5678, na,na,na,na,na,na)) library(zoo) na.locf(mydata) # name number # 1 sergio 1234 # 2 sergio 1234 # 3 sergio 1234 # 4 sergio 1234 # 5 sergio 1234 # 6 john 5678 # 7 john 5678 # 8 john 5678 # 9 john 5678 # 10 john 5678 # 11 john 5678 # 12 john 5678
if prefer not use package, here's might work:
locf <- function(x) { <- cumsum(!is.na(x)) ave(x, a, fun = function(x) x[1]) } mydata[] <- lapply(mydata, locf)
Comments
Post a Comment