If I use the na.locf function to replace each NA with the most recent non-NA prior to it, then> na.locf(c(NA,NA,1,4,NA,2))[1] 1 1 1 4 4 2 I want to keep leading NA's, and this is what I want NA NA 1 4 4 2 How can I do it? The following do not work:> na.locf(c(NA,NA,1,4,NA,2), na.rm=FALSE)Error in na.locf(c(NA, NA, 1, 4, NA, 2), na.rm = FALSE) : unused argument (na.rm = FALSE)> na.locf(c(NA,NA,1,4,NA,2), na.rm=TRUE)Error in na.locf(c(NA, NA, 1, 4, NA, 2), na.rm = TRUE) : unused argument (na.rm = TRUE) Thank you very much! John [[alternative HTML version deleted]]
Duncan Murdoch
2019-Feb-27 04:06 UTC
[R] Replacing each NA with the most recent non-NA prior to it
On 26/02/2019 10:34 p.m., John wrote:> If I use the na.locf function to replace each NA with the most recent > non-NA prior to it, then > >> na.locf(c(NA,NA,1,4,NA,2)) > [1] 1 1 1 4 4 2 > > I want to keep leading NA's, and this is what I want > NA NA 1 4 4 2 > > How can I do it? > > The following do not work: > >> na.locf(c(NA,NA,1,4,NA,2), na.rm=FALSE) > Error in na.locf(c(NA, NA, 1, 4, NA, 2), na.rm = FALSE) : > unused argument (na.rm = FALSE) >> na.locf(c(NA,NA,1,4,NA,2), na.rm=TRUE) > Error in na.locf(c(NA, NA, 1, 4, NA, 2), na.rm = TRUE) : > unused argument (na.rm = TRUE) > > > Thank you very much!There are at least two packages (zoo and imputeTS) which have na.locf functions. The one in zoo does what you want: > zoo::na.locf(c(NA,NA,1,4,NA,2), na.rm=FALSE) [1] NA NA 1 4 4 2 Duncan Murdoch
Thanks! That works!! Duncan Murdoch <murdoch.duncan at gmail.com> ? 2019?2?27? ?? ??12:06???> On 26/02/2019 10:34 p.m., John wrote: > > If I use the na.locf function to replace each NA with the most recent > > non-NA prior to it, then > > > >> na.locf(c(NA,NA,1,4,NA,2)) > > [1] 1 1 1 4 4 2 > > > > I want to keep leading NA's, and this is what I want > > NA NA 1 4 4 2 > > > > How can I do it? > > > > The following do not work: > > > >> na.locf(c(NA,NA,1,4,NA,2), na.rm=FALSE) > > Error in na.locf(c(NA, NA, 1, 4, NA, 2), na.rm = FALSE) : > > unused argument (na.rm = FALSE) > >> na.locf(c(NA,NA,1,4,NA,2), na.rm=TRUE) > > Error in na.locf(c(NA, NA, 1, 4, NA, 2), na.rm = TRUE) : > > unused argument (na.rm = TRUE) > > > > > > Thank you very much! > > > There are at least two packages (zoo and imputeTS) which have na.locf > functions. The one in zoo does what you want: > > > zoo::na.locf(c(NA,NA,1,4,NA,2), na.rm=FALSE) > [1] NA NA 1 4 4 2 > > Duncan Murdoch > > >[[alternative HTML version deleted]]