oercim
oercim

Reputation: 1848

Filling NA's in a data frame according to a rule at R

Let I have such a data frame(df):

date           x     y
01-01-2016    43    14
02-01-2016    32    NA
03-01-2016    42    NA
04-01-2016    35    19
05-01-2016    45    NA
06-01-2016    65    NA
07-01-2016    39    NA
08-01-2016    39    24

I want to add two new colums(z1 and z2) to the above data frame(df)

date           x     y    z1     z2
01-01-2016    43    14    14     14
02-01-2016    32    NA    14     19 
03-01-2016    42    NA    14     19
04-01-2016    35    19    19     19
05-01-2016    45    NA    19     24
06-01-2016    65    NA    19     24
07-01-2016    39    NA    19     24
08-01-2016    39    24    24     24

z1 rule is like below:

z2 rule is like below:

How can I do that in R? I will be very glad for any help. Thanks a lot.

Upvotes: 0

Views: 94

Answers (1)

akuiper
akuiper

Reputation: 214927

You need a forward fill (z1) and a backward fill (z2); You can do this with zoo::na.locf by specifying the fromLast parameter, the docs as below:

logical. Causes observations to be carried backward rather than forward. Default is FALSE. With a value of TRUE this corresponds to NOCB (next observation carried backward)

library(zoo)
df$z1 <- na.locf(df$y, fromLast = FALSE)
df$z2 <- na.locf(df$y, fromLast = TRUE)
df
#        data  x  y z1 z2
#1 01-01-2016 43 14 14 14
#2 02-01-2016 32 NA 14 19
#3 03-01-2016 42 NA 14 19
#4 04-01-2016 35 19 19 19
#5 05-01-2016 45 NA 19 24
#6 06-01-2016 65 NA 19 24
#7 07-01-2016 39 NA 19 24
#8 08-01-2016 39 24 24 24

Or a tidyverse approach, with the fill function where you can specify the direction up/down:

library(tidyverse)
df %>% 
    mutate(z1 = y, z2 = y) %>% 
    fill(z1, .direction = "down") %>% 
    fill(z2, .direction = "up")

#        data  x  y z1 z2
#1 01-01-2016 43 14 14 14
#2 02-01-2016 32 NA 14 19
#3 03-01-2016 42 NA 14 19
#4 04-01-2016 35 19 19 19
#5 05-01-2016 45 NA 19 24
#6 06-01-2016 65 NA 19 24
#7 07-01-2016 39 NA 19 24
#8 08-01-2016 39 24 24 24

Upvotes: 7

Related Questions