Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill dataframe column with incremental sequence number

Tags:

r

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.

like image 647
B_Real Avatar asked Jul 15 '26 08:07

B_Real


1 Answers

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)
like image 161
Nikolay Nenov Avatar answered Jul 17 '26 20:07

Nikolay Nenov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!