I'm trying to fill the remaining NA values of my dataframe column with incremental numbers, continuing from the last known number. Here's a sample of the problem:
df <- data.frame(var1 = c(1:5), var2 = c(1,2,3, NA, NA))
I want the two NA's in var2 to be 4 and 5 (i.e. a continuation from 1,2,3 ... to the end). I've got about 15 columns and 10,000 cases. Feels like it should be simple, the equivalent in excel is highlighting two previous cells and dragging the selection down (i.e. an extend)).
I looked at the complete() function in tidyr but I don't really understand it.
you can do:
df <- data.frame(var1 = c(1:5), var2 = c(1,2,3, NA, NA))
df$repl <- seq_len(nrow(df))
df$var2 <- ifelse(is.na(df$var2),
df$repl, df$var2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With