0

I have a dataframe df with NA values in between. Can I fill those NA values with specific column values

df
COlA   COlB     ColC
1       df        3
1       fsg       4
1       sdf       5
1       sd        6
NA      NA        67
NA      NA        54
2       adf       13
2       afsg      14
2       asdf      15
2       asd       16
NA      NA        77
NA      NA        84

Expected output

df
COlA   COlB     ColC
1       df        3
1       fsg       4
1       sdf       5
1       sd        6
1       NA        67
1       NA        54
2       adf       13
2       afsg      14
2       asdf      15
2       asd       16
2       NA        77
2       NA        84

So Is it possible to fill COLA with the above values?

imran p
  • 332
  • 2
  • 12
  • 1
    Have a look at `na.fill()` from package `zoo`. https://stackoverflow.com/questions/42570024/r-fill-missing-value-with-prior-values – jogo Jan 24 '20 at 14:25
  • 2
    Duplicate: https://stackoverflow.com/questions/7735647/replacing-nas-with-latest-non-na-value – user2474226 Jan 24 '20 at 14:26
  • Does this answer your question? [R: fill missing value with prior values](https://stackoverflow.com/questions/42570024/r-fill-missing-value-with-prior-values) – jogo Jan 24 '20 at 14:28
  • Does this answer your question? [Replacing NAs with latest non-NA value](https://stackoverflow.com/questions/7735647/replacing-nas-with-latest-non-na-value) – Oleg Russkin Jan 24 '20 at 14:48

2 Answers2

0

You can use the fill function in the tidyr package.

library(tidyr)

fill(df, COlA)

   COlA COlB ColC
1     1   df    3
2     1  fsg    4
3     1  sdf    5
4     1   sd    6
5     1 <NA>   67
6     1 <NA>   54
7     2  adf   13
8     2 afsg   14
9     2 asdf   15
10    2  asd   16
11    2 <NA>   77
12    2 <NA>   84
Aron Strandberg
  • 3,040
  • 9
  • 15
0

We can use na.locf from zoo

library(zoo)
df$COlA <- na.locf(df$COlA)
akrun
  • 874,273
  • 37
  • 540
  • 662