I have a dataframe in which a column (x) has some missing values and I would like to create a new column (y) replacing these NAs with the nearest value already existing. Also I would like that if the distance is the same both ways, I get the mean of both.
Here is an example of what I mean:
data <- data.frame(x = c(2, 3, 3, NA, NA, 4, NA, 3, 2, NA, NA, NA, 4))
The dataframe I would like to obtain would be that:
x | y |
---|---|
2 | 2 |
3 | 3 |
3 | 3 |
NA | 3 |
NA | 4 |
4 | 4 |
NA | 3.5 |
3 | 3 |
2 | 2 |
NA | 2 |
NA | 3 |
NA | 4 |
4 | 4 |
Thanks in advance