Home > Mobile >  R: Add rows for missing observations in time series data (days and beeps)
R: Add rows for missing observations in time series data (days and beeps)

Time:01-19

I have some time series data (see bellow). For every subject (Rid), there should be a row per day (0-12) and within each day a row per beep (1-5).

How can I add these missing rows, so that every subject has 65 rows consisting of day 0-12 and beeps 1-5, and fill them with NA's?

     Rid dayno beepno
1   R322     0      2
2   R322     0      4
3   R322     0      5
4   R322     1      4
5   R322     2      1
6   R322     2      2

15  R322     6      4
16  R322     6      5
17  R322     7      1
18  R322     7      2

26  R323     1      3
27  R323     1      4
28  R323     2      2
29  R323     2      3
30  R323     2      5

43  R306     1      4
44  R306     0      4
45  R306     0      1
46  R306     1      1
47  R306     1      2
48  R306     1      3
49  R306     1      4

CodePudding user response:

Think I found an answer:

library(dplyr)
library(tidyr)

data_2 <- group_by(data, Rid) %>% 
  complete(dayno = 0:12, beepno = 1:5)

CodePudding user response:

Pivot_wider from the tidyverse should help, it'll create the extra entries and then you can return the data shape using pivot_longer. More steps will be needed than this, but it'll let you get started.

library(tidyverse)
pivot_wider(data,
names_from=dayno,
values_from=beepno
values_fill=0)
  •  Tags:  
  • Related