Suppose I have the following unbalance pandel data:
unbalanced.panel = structure(list(firm = c("A", "A", "A", "A", "B", "B", "A", "A",
"B", "C", "C"), ind = c(1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1), year = c(2010,
2011, 2012, 2013, 2011, 2013, 2011, 2012, 2010, 2012, 2013),
charac1 = c("x", "x", "x", "x", "y", "y", "z", "z", "g",
"h", "h"), var1 = c(11, 12, 13, 14, 15, 18, 15, 29, 31, 13,
2)), row.names = c(NA, -11L), class = c("tbl_df", "tbl",
"data.frame"))
firm ind year charac1 var1
<chr> <dbl> <dbl> <chr> <dbl>
1 A 1 2010 x 11
2 A 1 2011 x 12
3 A 1 2012 x 13
4 A 1 2013 x 14
5 B 2 2011 y 15
6 B 2 2013 y 18
7 A 2 2011 z 15
8 A 2 2012 z 29
9 B 1 2010 g 31
10 C 1 2012 h 13
11 C 1 2013 h 2
Where each unique group (individual) is identified by the combination of firm
and ind
, i.e. individual "A1" is different from "A2" individual. And the time index is given by year
variable.
What I want is to balance the panal data (index = (individual = firm-ind, time = year)) filling the implicit missing gaps with NA's.
The desired result is as follows:
firm ind year charac1 var1
<chr> <dbl> <dbl> <chr> <dbl>
1 A 1 2010 x 11
2 A 1 2011 x 12
3 A 1 2012 x 13
4 A 1 2013 x 14
5 B 2 2010 y NA
6 B 2 2011 y 15
7 B 2 2012 y NA
8 B 2 2013 y 18
9 A 2 2010 z NA
10 A 2 2011 z 15
11 A 2 2012 z 29
12 A 2 2013 z NA
13 B 1 2010 g 31
14 B 1 2011 g NA
15 B 1 2012 g NA
16 B 1 2013 g NA
17 C 1 2010 h NA
18 C 1 2011 h NA
19 C 1 2012 h 13
20 C 1 2013 h 2
I tried to use plm::make.pbalanced(unbalanced.panel, balance.type = "fill")
but I got the following error:
Error in mode<-(tmp, value = id_orig_typeof) : invalid to change the storage mode of a factor
I even tried to used tidyr::complete()
, but it doesn't help to achieve my desired balanced panel.
These are my request: When an unique individual (firm-ind) is missing a year row, time-variant variables (var1) must be filled with NA, but time-invariant variables such as characteristics (charact1) should be filled with the unique value.
What's the problem with tidyr::complete()
approach? It doesn't allow me to differentiate between time-invariant and time-variant variables to be filled or expanded. And it doesn't identify uniquely individual-index (in this case firm-ind).
unbalanced.panel >%>
tidyr::complete(firm, year, nesting(var1))
Above code makes appear a new individual "C2" and fills with NA the time-invariant variables.