Fill the empty upper rows with immediate next rows of same ID

Data i have

id <- c(1,1,1,2,2,3,3,4,4,4)
a  <- c(NA,NA,1,5,2,NA,7,NA,NA,8)
b  <- c(1,2,3,4,5,6,7,8,9,10)

df <- data.frame(id,a,b)

Data i want

a2 <- c(1,1,1,5,2,7,7,8,8,8)

df2 <- data.frame(id,a2,b)

I just want to fill NA's in "a" column with immediate next filled column of same id.
if many same id have many NA's at first and only one filled value at last row, fill all NA's with the filled value of the same id.(just like id 1 case in example)

Some one help me to do this.

Thank you

It's unclear if you want to replace the NA values from id or from b; neither gives a2 I've assumed b

suppressPackageStartupMessages({
  library(dplyr)
})
id <- c(1,1,1,2,2,3,3,4,4,4)
a  <- c(NA,NA,1,5,2,NA,7,NA,NA,8)
b  <- c(1,2,3,4,5,6,7,8,9,10)

# avoid using function names
my_df <- data.frame(id,a,b) 

my_df %>% mutate(a = ifelse(is.na(a),b,a))
#>    id a  b
#> 1   1 1  1
#> 2   1 2  2
#> 3   1 1  3
#> 4   2 5  4
#> 5   2 2  5
#> 6   3 6  6
#> 7   3 7  7
#> 8   4 8  8
#> 9   4 9  9
#> 10  4 8 10

Created on 2020-12-03 by the reprex package (v0.3.0.9001)

Thank you.

I want to replace the NA values with, value given in below row in same column with same id.

Kind of filling rows up.

Hope i am clear this time! sorry for inconvenience.

How do you intend to handle the case when the last row of an id has an NA column a? Is the idea to keep looking until another run of rows of the same id is encountered?

library(dplyr)
library(tidyr)

sample_df <- data.frame(
          id = c(1, 1, 1, 2, 2, 3, 3, 4, 4, 4),
           a = c(NA, NA, 1, 5, 2, NA, 7, NA, NA, 8),
           b = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
)

sample_df %>%
    group_by(id) %>% 
    fill(a, .direction = "up")
#> # A tibble: 10 x 3
#> # Groups:   id [4]
#>       id     a     b
#>    <dbl> <dbl> <dbl>
#>  1     1     1     1
#>  2     1     1     2
#>  3     1     1     3
#>  4     2     5     4
#>  5     2     2     5
#>  6     3     7     6
#>  7     3     7     7
#>  8     4     8     8
#>  9     4     8     9
#> 10     4     8    10

Created on 2020-12-04 by the reprex package (v0.3.0.9001)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.