R-每两行求和,然后除以该和中的第一行

R-每两行求和,然后除以该和中的第一行,r,R,我有一个如下的数据帧 a b 24 11.67 -1 39 8.14 1 42 8.12 1 90 10.50 -1 137 13.53 -1 405 47.45 1 416 58.11 -1 454 54.13 1 467 47.82 1 500 59.31 -1 508 61.18 -1 598 51.67

我有一个如下的数据帧

      a          b
24    11.67     -1
39     8.14      1
42     8.12      1
90    10.50     -1
137   13.53     -1
405   47.45      1
416   58.11     -1
454   54.13      1
467   47.82      1
500   59.31     -1
508   61.18     -1
598   51.67      1
626   49.86      1
663   58.47     -1
677   64.85     -1
919   91.15      1
926   82.79      1
974  111.51     -1
1024  85.33      1
1103 118.79     -1
因此,在本例中,我想要的是以下列方式的列表:

(11.67*-1+8.14*1)/11.67
(8.12*1+10.50*-1)/8.12
(13.52*-1+47.45*1)/13.53
.
.
.
that is --> 
(a1*b1)+(a2*b2)/a1
(a3*b3)+(a4*b4)/a3
.
.
.

我不知道从哪里开始。因此,我们非常感谢您的帮助。

您可以执行以下操作:

ind_denominator <- seq(1, nrow(dat), by=2)
ind_sum <- rep(ind_denominator, each=2)
tapply(dat$a*dat$b, ind_sum, sum)/dat$a[ind_dividor]

另一个带有
rowsum()的选项


这里是一种仅使用
seq
的不同方法:

(df[seq(1,nrow(df),2),1]*df[seq(1,nrow(df),2),2] + df[seq(2,nrow(df),2),1]*df[seq(2,nrow(df),2),2])/df[seq(1,nrow(df),2),1]
子字幕信息:

http://www.statmethods.net/management/subset.html
https://stat.ethz.ch/R-manual/R-devel/library/base/html/subset.html
https://stat.ethz.ch/R-manual/R-devel/library/base/html/nrow.html
如果您不想在R(*)中执行for循环,那么这是关于子集数据的:“:”运算符和seq()或sequence运算符*循环并不像人们想象的那个样糟糕,特别是通过对子集计算函数[1]的elegent使用,比如pratz中的tapply(),或者pratz中的聚合函数rowsum()的elegent使用。但是,假设您不需要循环,那么您可以更正如下代码:

mydata <- data.frame(a,b) # #Your data either matrix or data frame format. 
# In this case I used vectors or column a and b 
indexa <-  seq(1,nrow(mydata)-1, by = 2) #we to index a from 1 to 1 minus the last row
indexb <- seq(2,nrow(mydata), by = 2) #we want to index b from 2 to the last row
ans <- (mydata$a[1:indexa]*mydata$b[1:indexa] +
         mydata$a[2:indexb]*mydata$b[2:indexb])/(mydata$a[1:indexa])
ans = 
 [1] -0.30248500 -0.29310345  2.50702143 -0.06849079 -0.24027604 -0.15544296 -0.17268351
 [8]  0.40555127 -0.34690180 -0.39212469

mydata我正要发布一个解决方案,你抢先一步。就像这里使用的
tapply
一样,您的解决方案比我的更优雅。我建议您尝试编写第一个循环。并学习如何存储每次迭代的结果:)一条很长的线
http://www.statmethods.net/management/subset.html
https://stat.ethz.ch/R-manual/R-devel/library/base/html/subset.html
https://stat.ethz.ch/R-manual/R-devel/library/base/html/nrow.html
mydata <- data.frame(a,b) # #Your data either matrix or data frame format. 
# In this case I used vectors or column a and b 
indexa <-  seq(1,nrow(mydata)-1, by = 2) #we to index a from 1 to 1 minus the last row
indexb <- seq(2,nrow(mydata), by = 2) #we want to index b from 2 to the last row
ans <- (mydata$a[1:indexa]*mydata$b[1:indexa] +
         mydata$a[2:indexb]*mydata$b[2:indexb])/(mydata$a[1:indexa])
ans = 
 [1] -0.30248500 -0.29310345  2.50702143 -0.06849079 -0.24027604 -0.15544296 -0.17268351
 [8]  0.40555127 -0.34690180 -0.39212469