My dataframe looks like:
df <- data.frame(ID=c("A", "A", "A", "A",
"B", "B", "B", "B",
"C", "C", "C", "C",
"D", "D", "D", "D"),
grade=c("KG", "01", "02", "03",
"KG", "01", "02", "03",
"KG", "01", "02", "03",
"KG", "01", "02", "03"),
year=c(2002, 2003, NA, 2005,
2007, NA, NA, 2010,
NA, 2005, 2006, NA,
2009, 2010, NA, NA))
I would like to be able to impute the missing year
values by ID
, with the following desired results:
wanted_df <- data.frame(ID=c("A", "A", "A", "A",
"B", "B", "B", "B",
"C", "C", "C", "C",
"D", "D", "D", "D"),
grade=c("KG", "01", "02", "03",
"KG", "01", "02", "03",
"KG", "01", "02", "03",
"KG", "01", "02", "03"),
year=c(2002, 2003, 2004, 2005,
2007, 2008, 2009, 2010,
2004, 2005, 2006, 2007,
2009, 2010, 2011, 2012))
I have attempted to impute the values using:
lag()
andlead()
functions- Joining to a dataframe consisting of years
Neither have worked. Any help would be greatly appreciated. Thank you.