Posts

Showing posts from March 18, 2019

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

Image
6 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...