Reputation: 2226
I have a dataset like this
pos value
1 20
2 30
4 50
5 50
9 30
You will note that 3, 6,7,8
positions and respective value entries are missing. I would like to fill them in with values corresponding to 0 so that the data looks like this
pos value
1 20
2 30
3 0
4 50
5 50
6 0
7 0
8 0
9 30
Any ideas on how to achieve this in R?
Upvotes: 1
Views: 78
Reputation: 887881
We can use complete
from tidyr
library(tidyr)
df1 %>%
complete(pos = full_seq(pos, 1), fill = list(value=0))
# A tibble: 9 × 2
# pos value
# <dbl> <dbl>
#1 1 20
#2 2 30
#3 3 0
#4 4 50
#5 5 50
#6 6 0
#7 7 0
#8 8 0
#9 9 30
If we want to continue until 20
df1 %>%
complete(pos = full_seq(c(pos,20), 1), fill = list(value=0))
Upvotes: 3