[R] HELP ME: Fill NA Values from the previous Non-NA Values

PIKAL Petr petr.pikal at precheza.cz
Thu Mar 16 14:38:33 CET 2017


Hi

You can achieve exactly what you want by using ave/na.locf twice

dat<-data.frame(ie=rep(letters[1:3], each=3), iw=rnorm(9))
dat[c(3, 4),2]<-NA
> dat
  ie          iw
1  a  1.07254438
2  a  0.53067188
3  a          NA
4  b          NA
5  b -0.09767088
6  b -1.02719060
7  c  2.35787246
8  c -0.07513048
9  c -0.17164728

dat$iw <- ave(dat$iw, dat$ie, FUN=function(x) na.locf(x, na.rm=FALSE))
dat$iw <- ave(dat$iw, dat$ie, FUN=function(x) na.locf(x, na.rm=FALSE, fromLast=TRUE))

> dat
  ie          iw
1  a  1.07254438
2  a  0.53067188
3  a  0.53067188
4  b -0.09767088
5  b -0.09767088
6  b -1.02719060
7  c  2.35787246
8  c -0.07513048
9  c -0.17164728
>

Cheers
Petr

> -----Original Message-----
> From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Allan
> Tanaka
> Sent: Thursday, March 16, 2017 3:16 AM
> To: William Dunlap <wdunlap at tibco.com>
> Cc: r-help at r-project.org
> Subject: Re: [R] HELP ME: Fill NA Values from the previous Non-NA Values
>
>  Hi. Thanks for the function. My bad, after looking at the csv file, it seems that
> NA values come not only from previous Non-NA values but also from the
> next Non-NA values. Example:
> | NCQ05 | 11.395 |
> | NCQ05 | 11.395 |
> | NCQ05 |  |
> | NCQ06 |  |
> | NCQ06 | 13 |
> | NCQ06 | 13 |
>
>
> If i use the function, then the blank row would be filled with 11.395, instead
> of filling with 11.395 and 13.
> Does it mean that the function can be modified like this?
> locf2 <- function(x, initial=NA, IS_BAD = is.na) {
>     # Replace 'bad' values in 'x' with last previous non-bad value.
>     # If no previous non-bad value, replace with 'initial'.
>     stopifnot(is.function(IS_BAD))
>     good <- !IS_BAD(x)
>     stopifnot(is.logical(good), length(good) == length(x), !anyNA(good))
>     i <- cumsum(good)
>     x <- x[c(1,which(good))][i+1]
>     x <- x[c(1,which(good))][i+2]
>     x[i==0] <- initial
>     x
> }    On Thursday, 16 March 2017, 1:17, William Dunlap <wdunlap at tibco.com>
> wrote:
>
>
>  You could use the following function
>
> locf2 <- function(x, initial=NA, IS_BAD = is.na) {
>     # Replace 'bad' values in 'x' with last previous non-bad value.
>     # If no previous non-bad value, replace with 'initial'.
>     stopifnot(is.function(IS_BAD))
>     good <- !IS_BAD(x)
>     stopifnot(is.logical(good), length(good) == length(x), !anyNA(good))
>     i <- cumsum(good)
>     x <- x[c(1,which(good))][i+1]
>     x[i==0] <- initial
>     x
> }
>
> as in
>
> > locf2(c("", "A", "B", "", "", "C", ""), IS_BAD=function(x)x=="",
> > initial="---")
> [1] "---" "A"  "B"  "B"  "B"  "C"  "C"
> > locf2(factor(c(NA,"Small","Medium",NA,"Large",NA,NA,NA,"Small")))
> [1] <NA>  Small  Medium Medium Large  Large  Large  Large  Small
> Levels: Large Medium Small
> > locf2(c(12, NA, 10, 11, NA, NA))
> [1] 12 12 10 11 11 11
>
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
>
>
> On Wed, Mar 15, 2017 at 4:08 AM, Allan Tanaka <allantanaka11 at yahoo.com>
> wrote:
> > The following is an example:
> >
> > | Item_Identifier | Item_Weight |
> > | FDP10 | 19 |
> > | FDP10 |  |
> > | DRI11 | 8.26 |
> > | DRI11 |  |
> > | FDW12 | 8.315 |
> > | FDW12 |  |
> >
> >
> > The following is the one that i want to be. That is, filling NA values from the
> previous Non-NA values.
> > | Item_Identifier | Item_Weight |
> > | FDP10 | 19 |
> > | FDP10 | 19 |
> > | DRI11 | 8.26 |
> > | DRI11 | 8.26 |
> > | FDW12 | 8.315 |
> > | FDW12 | 8.315 |
> >
> >
> > My current code data frame: train <- read.csv("Train.csv",
> > header=T,sep = ",",na.strings = c(""," ",NA))
> >
> >
> > Some people suggest to use na.locf function but in my case, i don't have
> numeric unique values in my Item_Identifier coloumn but rather it's
> characters. Not sure what to solve this problem.
> >
> >
> >        [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> > http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
>
>
>
>       [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.

________________________________
Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou určeny pouze jeho adresátům.
Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze svého systému.
Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či zpožděním přenosu e-mailu.

V případě, že je tento e-mail součástí obchodního jednání:
- vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, a to z jakéhokoliv důvodu i bez uvedení důvodu.
- a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany příjemce s dodatkem či odchylkou.
- trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným dosažením shody na všech jejích náležitostech.
- odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu případně osobě, kterou adresát zastupuje, předloženy nebo jejich existence je adresátovi či osobě jím zastoupené známá.

This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.

In case that this e-mail forms part of business dealings:
- the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
- if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
- the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
- the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.


More information about the R-help mailing list