Priya
Priya

Reputation: 13

How to fill missing NA's with sequence in numeric column in R

Example data: week = c(0,1,2,3,4,NA,6,NA,NA,NA,10)

Current solution that I am using is:

ifelse(is.na(week),na.locf(week)+1,week)

But it outputs: 0 1 2 3 4 5 6 7 7 7 10

Desired Output: 0 1 2 3 4 5 6 7 8 9 10

Any help will be appreciated, Thank you in advance!

Upvotes: 1

Views: 698

Answers (2)

Maël
Maël

Reputation: 51914

The zoo package has a function for that specific purpose: na.spline.

week = c(0,1,2,3,4,NA,6,NA,NA,NA,10)

zoo::na.spline(week)
# [1]  0  1  2  3  4  5  6  7  8  9 10

Upvotes: 1

Ben
Ben

Reputation: 30474

With purrr you can try the following. If missing (NA) then increase by 1, otherwise, keep the value.

library(purrr)

accumulate(week, ~ifelse(is.na(.y), .x + 1, .y))

Output

[1] 0 1 2 3 4 5 6 7 8 9

Upvotes: 6

Related Questions