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
260 views
in Technique[技术] by (71.8m points)

dataframe - in R, How to sum by flowing row in a data frame

I have df(A) (ncol=1,nrow=1356)

col1
 5
 7
 9
 3
 2
 3.8
 24
 2.7
 12
 11
 23
 .... to 1356 row...

i would like the sum from the first row to the fifth row, and after from the second row to the seventh row, and so on. Furthermore each value is moltiplicate for a fraction of the number of row. The expected results is, for example:

5*1/5 + 7*2/5 + 9*3/5 + 3*4/5 + 2*5/5= (result)
7*1/5 + 9*2/5 + 3*3/5 + 2*4/5 + 3.8*5/5= (result)
9*1/5 + 3*2/5 + 2*3/5 + 3.8*4/5 + 24*5/5= (result)
and so on for the 1356 row

In synthesis the sum is every 5 row, roll the data row by row. Thank you in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I would use my favorite R function, filter:

DF <- read.table(text = "col1
                 5
                 7
                 9
                 3
                 2
                 3.8
                 24
                 2.7
                 12
                 11
                 23", header = TRUE)

5*1/5 + 7*2/5 + 9*3/5 + 3*4/5 + 2*5/5
#[1] 13.6
7*1/5 + 9*2/5 + 3*3/5 + 2*4/5 + 3.8*5/5
#[1] 12.2
9*1/5 + 3*2/5 + 2*3/5 + 3.8*4/5 + 24*5/5
#[1] 31.24

c(na.omit(stats::filter(DF$col1, (5:1)/5)))
#[1] 13.60 12.20 31.24 25.58 30.48 32.58 44.88

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

...