r - How can I get mean of every n rows and keep the date index? -
i have dataframe year index , val index.
i create mean of every n rows of val , keep corresponding year index.
basically, output (for n=2)
year val 1990 mean(row1,row2) 1992 mean(row3,row4) 1994 mean(row5,row6) 1996 mean(row7,row8)
how can this?
structure(list(year = c(1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013), val = c(84l, 67l, 72l, 138l, 111l, 100l, 221l, 108l, 204l, 125l, 82l, 157l, 175l, 252l, 261l, 185l, 146l, 183l, 245l, 172l, 98l, 216l, 89l, 144l)), .names = c("year", "val"), row.names = 13:36, class = "data.frame")
a short one-liner solution data.table
:
library(data.table) setdt(df)[,.(val=mean(val)), year-0:1] # year val # 1: 1990 75.5 # 2: 1992 105.0 # 3: 1994 105.5 # 4: 1996 164.5 # 5: 1998 164.5 # 6: 2000 119.5 # 7: 2002 213.5 # 8: 2004 223.0 # 9: 2006 164.5 #10: 2008 208.5 #11: 2010 157.0 #12: 2012 116.5
Comments
Post a Comment