Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

r - How can I get mean of every n rows and keep the date index?

I have a dataframe with a year index and a val index.

I would like to create a mean of every n rows of val and keep the corresponding year index.

Basically, the output would be (for n=2)

year val
1990 Mean(row1,row2)
1992 Mean(row3,row4)
1994 Mean(row5,row6)
1996 Mean(row7,row8)

How can I do 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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A short one-liner solution with 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...