hklovs
hklovs

Reputation: 642

replace NA in same group with value

DF<-data.frame(id=c(1,1,2,3,3),code=c("A","NA","A","NA","E"))
> DF
  id code
1  1    A
2  1   NA
3  2    A
4  3   NA
5  3    E

Desired output:

  id code
1  1    A
2  1    A
3  2    A
4  3    E
5  3    E

I want to replace NA in each group with non-NA value.

Best H

Upvotes: 2

Views: 59

Answers (1)

akrun
akrun

Reputation: 886938

We can use

library(dplyr)
DF %>%
   group_by(id) %>%
    mutate(code = first(code[!is.na(cod)]))

Or could also be fill if the intention is to replace the NA with the previous non-NA

library(tidyr)
DF %>%
   group_by(id) %>%
   fill(code)

Upvotes: 2

Related Questions