Suppose I have a data frame which looks like this
ID A B C D Month
1 X M 5 1 3
1 X K 4 2 4
1 X K 3 7 5
1 X K 2 6 6
2 Y L 5 8 1
2 Y L 2 3 2
2 Y M 5 1 3
2 Y K 2 7 5
2 Y M 2 8 6
3 Z K 5 3 1
3 Z M 6 3 2
3 Z M 5 8 3
3 Z K 4 2 4
- In this data
ID
andA
are unique variables, - while
B,C,D,Month
can change their value Month
has6
factor values from 1 to 6B
have3
factor value from K,L,MC,D
can have any value.
I want this data to become like this
ID A B C D Month
1 X 0 0 0 1
1 X 0 0 0 2
1 X M 5 1 3
1 X K 4 2 4
1 X K 3 7 5
1 X K 2 6 6
2 Y L 5 8 1
2 Y L 2 3 2
2 Y M 5 1 3
2 Y 0 0 0 4
2 Y K 2 7 5
2 Y M 2 8 6
3 Z K 5 3 1
3 Z M 6 3 2
3 Z M 5 8 3
3 Z K 4 2 4
3 Z 0 0 0 5
3 Z 0 0 0 6
It should fill in the missing rows by keeping the unique variables values same and filling in the varying ones with zero.
I can use zoo
library to fill in the missing values but how to fill in the complete missing rows?