在R中,如何通过在数据框中流动行来求和

时间:2016-01-18 09:54:51

标签: r dataframe sum

我有df(A)(ncol = 1,nrow = 1356)

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

我想要从第一行到第五行的总和,以及从第二行到第七行之后的总和,依此类推。此外,对于行数的一小部分,每个值都是moltiplicate。预期的结果是,例如:

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

在综合中,总和是每5行,逐行滚动数据。 提前谢谢。

2 个答案:

答案 0 :(得分:2)

我会使用我最喜欢的R函数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

答案 1 :(得分:0)

我们可以使用- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading { double heading = newHeading.trueHeading; double headingDegrees = (heading*M_PI/180); CLLocationDirection trueNorth = [newHeading trueHeading]; [mapView_ animateToBearing:trueNorth]; }

中的shift
data.table

或其他选项

library(data.table)
m1 <- na.omit(do.call(cbind, shift(df1$col1, 0:4, type="lead")))
rowSums(m1*(1:5)[col(m1)]/5) 
#[1] 13.60 12.20 31.24 25.58 30.48 32.58 44.88