Completing the NAs of a Tibble in R

Viewed 53

I have a database in R where there are some NAs in the variables. I would like to apply a logic function where the NAs would be filled with the immediately preceding value. Below is an example:

dados <- tibble::tibble(x = c(2, 3, 5, NA, 2, 1, NA, NA, 9, 3), 
                        y = c(4, 1, 9, NA, 8, 5, NA, NA, 1, 2)
)

# A tibble: 10 x 2
       x     y
   <dbl> <dbl>
 1     2     4
 2     3     1
 3     5     9
 4    NA    NA
 5     2     8
 6     1     5
 7    NA    NA
 8    NA    NA
 9     9     1
10     3     2

In this case, the 4th value of the variable x would be filled with a 5 and so on.

Thank you!

4 Answers

We could use fill from tidyr package:

ibrary(tidyr)
library(dplyr)

dados %>% 
    fill(c(x,y), .direction = "down")
       x     y
   <dbl> <dbl>
 1     2     4
 2     3     1
 3     5     9
 4     5     9
 5     2     8
 6     1     5
 7     1     5
 8     1     5
 9     9     1
10     3     2

We can use coalesce

library(dplyr)
dados %>% 
    mutate(across(x:y, ~ coalesce(., lag(.))))
# A tibble: 10 x 2
       x     y
   <dbl> <dbl>
 1     2     4
 2     3     1
 3     5     9
 4     5     9
 5     2     8
 6     1     5
 7     1     5
 8    NA    NA
 9     9     1
10     3     2
library(dplyr)

dados %>%
  mutate(x = case_when(is.na(x) ~ lag(x),
                       TRUE ~ x),
         y = case_when(is.na(y) ~ lag(y),
                       TRUE ~ y))

The follow will only work, if the first value in a column is not NA but I leave that for the sake of clear and easy code as an execise for you we can solve this for one column as in:

library(tibble)
dados <- tibble::tibble(x = c(2, 3, 5, NA, 2, 1, NA, NA, 9, 3), 
                        y = c(4, 1, 9, NA, 8, 5, NA, NA, 1, 2)
)

#where are the NA?
pos <- dados$x |>
         is.na() |>
         which()

# replace 
while(any(is.na(dados$x)))
  dados$x[pos] <- dados$x[pos-1]
dados
Related