如何使用R对数据帧中的每n(200)个观测值求和 [英] How to sum every nth (200) observation in a data frame using R

查看:190
本文介绍了如何使用R对数据帧中的每n(200)个观测值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的新手,因此非常感谢您的帮助!

I am new to R so any help is greatly appreciated!

我有10个变量中每个变量的278800个观测值的数据框,我试图创建第11个变量,该变量将特定变量/列的每200个观测值(或行)相加(sum(1:200,201: 399、400:599等.)类似于excel中的补偿功能. 我尝试将数据仅细分为感兴趣的变量,目的是添加一个新变量,该变量连续每200行累加一次,但是我无法弄清楚.我了解我的新变量"将产生1,394个数据点(278,800/200).我尝试使用rollapply函数,但是输出的总和不是200个块,而是1:200、2:201、3:202等.)

I have a data frame of 278800 observations for each of my 10 variables, I am trying to create an 11th variable that sums every 200 observations (or rows) of a specific variable/column (sum(1:200, 201:399, 400:599 etc.) Similar to the offset function in excel. I have tried subsetting my data to just the variable of interest with the aim of adding a new variable that continuously sums every 200 rows however I cannot figure it out. I understand my new "variable" will produce 1,394 data points (278,800/200). I have tried to use the rollapply function, however the output does not sum in blocks of 200, it sums 1:200, 2:201, 3:202 etc.)

谢谢

E

推荐答案

rollapply为此具有一个by=参数.这是一个使用n = 3而不是n = 200的较小示例.请注意1 + 2 + 3 = 6、4 + 5 + 6 = 15、7 + 8 + 9 = 24和10 + 11 + 12 = 33. /p>

rollapply has a by= argument for that. Here is a smaller example using n = 3 instead of n = 200. Note that 1+2+3=6, 4+5+6=15, 7+8+9=24 and 10+11+12=33.

# test data
DF <- data.frame(x = 1:12)

library(zoo)
n <- 3
rollapply(DF$x, n, sum, by = n)
## [1]  6 15 24 33

这篇关于如何使用R对数据帧中的每n(200)个观测值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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