0

I am trying to replace multiple rows having NA values with adjacent observed rows by group in a dataframe of R.

The data looks like:

| id | a1 | a2 | a3 | a4 | 
| ---|----|----|----|----|
| 1  | NA | NA | NA | NA |
| 1  | 1  | 1  | 1  | 1  |
| 1  | 2  | 2  | 2  | 2  |
| 1  | NA | NA | NA | NA | 

what I want to get is:

| id | a1 | a2 | a3 | a4 | 
| ---|----|----|----|----|
| 1  | 1  | 1  | 1  | 1  |
| 1  | 1  | 1  | 1  | 1  |
| 1  | 2  | 2  | 2  | 2  |
| 1  | 2  | 2  | 2  | 2  |

by replacing NA rows with adjacent observations (rows above and below) by group.

I tried:

sapply(1:nrow(df), function(i){if(is.na(df[i,2:5])){df[i,2:5] <<- df[(i+1),2:5]}})

sapply(1:nrow(df), function(i){if(is.na(df[i,2:5])){df[i,2:5] <<- df[(i-1),2:5]}})

but I cannot replace it by group.

Can anyone help this?

Cheers,

Terru_theTerror
  • 4,918
  • 2
  • 20
  • 39
RicNu
  • 1
  • You can use `tidyr::fill(df, a1:a4, .direction = "downup")`. If you mean with 'by group' that you want to group by id, you can use `library(dplyr)` and `df %>% group_by(id) %>% tidyr::fill(a1:a4, .direction = "downup") `. – Bas Jan 21 '21 at 08:49
  • @Bas Thank you so much! Your neat command perfectly works. – RicNu Jan 21 '21 at 09:09

0 Answers0