fill rows with NA based on vector sequence

Viewed 47

I have the following data.frame:

df=data.frame(x=c(1:3,8:10,15),y=rnorm(7))

x           y
1  0.05976784
2 -1.01992023
3 -1.16075185
8  0.48641141
9  0.54460423
10 -0.59915799
15 -0.60785783

I simply need to fill the rows with NA by following df$x sequence from 1 to 17.

Here my expected output:

x           y
1  0.05976784
2 -1.01992023
3 -1.16075185
4  NA
5  NA
6  NA
7  NA
8  0.48641141
9  0.54460423
10 -0.59915799
11  NA
12  NA
13  NA
14  NA
15 -0.60785783
16  NA
17  NA

How can I achieve this? Any suggestion?

2 Answers

Using base::match:

data.frame(x=1:17, df$y[match(1:17, df$x)])

We could use complete from tidyr

tidyr::complete(df, x = 1:17)

# A tibble: 17 x 2
#      x       y
#   <dbl>   <dbl>
# 1     1 -0.560 
# 2     2 -0.230 
# 3     3  1.56  
# 4     4   NA     
# 5     5   NA     
# 6     6   NA     
# 7     7   NA     
# 8     8  0.0705
# 9     9  0.129 
#10    10  1.72  
#11    11   NA     
#12    12   NA     
#13    13   NA     
#14    14   NA     
#15    15  0.461 
#16    16   NA     
#17    17   NA     

data

set.seed(123)
df=data.frame(x=c(1:3,8:10,15),y=rnorm(7))
Related