I'm using the tidyr complete()
and fill()
functions to extend (copy down) a dataframe so all ID elements have the same number of rows. The code posted at the bottom correctly extends all fields, with the exception of the "Bal2" column of the dataframe where a series of NA's should be extended. Any recommendations for how to correct this?
The NA values do serve a calculation purpose in the fuller code this is deployed in. Also please note that I have another code snippet for correctly extending the "Period_2" column so I don't need help with "Period_2". It's been omitted for code brevity.
The below illustrates the issue when generating the testDF
and testDF1
dataframes:
Code:
library(dplyr)
library(tidyr)
testDF <-
data.frame(
ID = c(rep(1,5),rep(50,3),rep(60,3)),
Period_1 = c(1:5,1:3,1:3),
Period_2 = c("2012-06","2012-07","2012-08","2012-09","2012-10","2013-06","2013-07","2013-08","2012-10","2012-11","2012-12"),
Bal1 = c(rep(10,5),21:23,36:34),
Bal2 = c(rep(12,8),rep(NA,3))
)
testDF1 <- testDF %>%
tidyr::complete(ID, nesting(Period_1)) %>%
tidyr::fill(Bal1, Bal2, .direction = "down")
testDF1 <- as.data.frame(testDF1)