I have a problem on creating a new variable Growth
, which equals to percentage change in Population
between closest years ending in “2” and “7”.
# dt
ID Population year
1 50 1995
1 60 1996
1 70 1997
1 80 1998
1 90 1999
1 100 2000
1 105 2001
1 110 2002
1 120 2003
1 130 2004
1 140 2005
1 150 2006
1 200 2007
1 300 2008
dt <- data.table::fread("ID Population year
1 50 1995
1 60 1996
1 70 1997
1 80 1998
1 90 1999
1 100 2000
1 105 2001
1 110 2002
1 120 2003
1 130 2004
1 140 2005
1 150 2006
1 200 2007
1 300 2008", header = T)
Growth = Percentage change in Pop between closest years ending in “2” and “7”. For example, in the year:
1996: (1997 Pop – 1992 Pop) / 1992 Pop
1997: (2002 Pop – 1997 Pop) / 1997 Pop
1998: (2002 Pop – 1997 Pop) / 1997 Pop
1999: (2002 Pop – 1997 Pop) / 1997 Pop
2000: (2002 Pop – 1997 Pop) / 1997 Pop
2001: (2002 Pop – 1997 Pop) / 1997 Pop
2002: (2007 Pop – 2002 Pop) / 2002 Pop
2003: (2007 Pop – 2002 Pop) / 2002 Pop
2004: (2007 Pop – 2002 Pop) / 2002 Pop
2005: (2007 Pop – 2002 Pop) / 2002 Pop
2006: (2007 Pop – 2002 Pop) / 2002 Pop
2007: (2012 Pop – 2007 Pop) / 2007 Pop
2008: (2012 Pop – 2007 Pop) / 2007 Pop
However, when I manipulate the Growth
, I need to do this by column ID
. Moreover, the range of year is from 1970 to 2018, really wide range. How can I do this in data.table
?
Growth
for 1996? 2012 Pop also doesn't exist – acylam