Replace all NA values for variable with one row equal to 0

  • A+
Category:Languages

Slightly difficult to phrase, as far as I saw none of the similar questions answered my problem.

I have a data.frame such as:

df1 <- data.frame(id = rep(c("a", "b"), each = 4),                   val = c(NA, NA, NA, NA, 1, 2, 2, 3))  df1    id val 1  a  NA 2  a  NA 3  a  NA 4  a  NA 5  b   1 6  b   2 7  b   2 8  b   3 

and I want to get rid of all the NA values (easy enough using e.g. filter() ) but make sure that if this removes all of one id value (in this case it removes every instance of "a") that one extra row is inserted of (e.g.) a = 0

so that:

  id val 1  a   0 2  b   1 3  b   2 4  b   2 5  b   3 

obviously easy enough to do this in a roundabout way but I was wondering if there's a tidy/elegant way to do this. I thought tidyr::complete() might help but not entirely sure how to apply it to a case like this

I don't care about the order of the rows

Cheers!

 


df1[is.na(df1)] <- 0 df1[!(duplicated(df1$id) & df1$val == 0), ]    id val 1  a   0 5  b   1 6  b   2 7  b   2 8  b   3 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: