R-数据框列中序列中数字的平均值
我正在尝试计算在另一列(x)内被依次计数(1、2、3等)的列(y)中的值的平均值。一个示例数据帧如下所示。
> df
x y
1 1 15
2 2 20
3 4 16
4 5 12
5 6 17
6 8 14
7 9 13
8 10 19
我想获得一个向量结果,该结果将读取数值序列中数字的平均值。所需的向量将读取:17.5 15.33333
我不确定产生所需结果的最佳方法,但是我尝试使用diff(df [,1])
to to to for loop for for loop to找到断点。
任何人都能提供的任何帮助将不胜感激。这是一个小示例数据集,但目标是将其应用于大数据集。
I am trying to calculate the mean of values in a column (y) that are being sequentially counted (1, 2, 3, etc.) within another column (x). An example dataframe is shown below.
> df
x y
1 1 15
2 2 20
3 4 16
4 5 12
5 6 17
6 8 14
7 9 13
8 10 19
I would like to get a vector result that will read out the mean values of numbers in a numerical sequence. The desired vector would read: 17.5 15 15.33333
I am not sure the best way to produce this desired result, but I have tried and failed to make a for loop using diff(df[,1])
to find the breakpoints.
Any help anyone could provide would be appreciated. This is a small example dataset, but the goal is to apply it to a large dataset.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
上创建分组列
从
diff
使用cumsum
在逻辑向量-Output数据
Create a grouping column from the
diff
usingcumsum
on a logical vector-output
data
更新:代码减少2行:
这是
dplyr
版本:x
使用cumsum(diff&gt创建组) ; = 2)
拉动
向量。Update: code reduced 2 lines:
Here is a
dplyr
version:x
cumsum(diff>=2)
pull
the vector.