在R中,如何通过在数据帧中流动行来求和 [英] in R, How to sum by flowing row in a data frame

查看:162
本文介绍了在R中,如何通过在数据帧中流动行来求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  col1 
5
7
9
3
2
3.8
24
2.7
12
11
23
....到1356行...

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

  5 * 1/5 + 7 * 2/5 + 9 * 3/5 + 3 * 4/5 + 2 * 5/5 =(结果)
7 * 1/5 + 9 * 2/5 + 3 * 3/5 + 2 * 4/5 + 3.8 * 5/5 =结果)
9 * 1/5 + 3 * 2/5 + 2 * 3/5 + 3.8 * 4/5 + 24 * 5/5 =(结果)
等1356行

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

解决方案

我们可以使用 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






或另一个选项

  m1<  -  embed(df1 $ col1,5) 
rowSums(m1 *(5:1)[col(m1)] / 5)
#[1] 13.60 12.20 31.24 25.58 30.48 32.58 44.88
pre>

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.

解决方案

We could use shift from 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


Or another option

 m1 <- embed(df1$col1,5)
 rowSums(m1*(5:1)[col(m1)]/5)
 #[1] 13.60 12.20 31.24 25.58 30.48 32.58 44.88

这篇关于在R中,如何通过在数据帧中流动行来求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆