0

what i have:

colA      colB     colC
pen        2        1
NA         yes      no
NA         yes      NA
pencil     1        2
NA         yes      no
NA         no       NA

what i want is all the NA in colA to be replaced with the preceding value.

colA      colB     colC
pen        2        1
pen        yes      no
pen        yes      NA
pencil     1        2
pencil     yes      no
pencil     no       NA

How can i get this in R.? Thank you for your help.

2 Answers2

1

Replacing all NA with preceding text value

df1$colA <- na.omit(df1$colA)[cumsum(!is.na(df1$colA))]

    colA colB colC
1    pen    2    1
2    pen  yes   no
3    pen  yes <NA>
4 pencil    1    2
5 pencil  yes   no
6 pencil   no <NA>
manotheshark
  • 4,297
  • 17
  • 30
1

The na.locf() function from the zoo packages does this in a rather simple manner.

df$colA <- na.locf(df$colA)

It obviously isn't a base solution but I use it all the time for stuff like this. It also has options for dealing with special scenarios (wanting to go int he other direction, leading NAs, etc.) which are discussed in ?zoo::na.locf()

cparmstrong
  • 799
  • 6
  • 23