在R中的数据帧中汇总分组记录

编程入门 行业动态 更新时间:2024-10-25 10:27:57
本文介绍了在R中的数据帧中汇总分组记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在R中有一个数据框,如下所示:

I have a data frame in R that looks like this:

> TimeOffset, Source, Length > 0 1 1500 > 0.1 1 1000 > 0.2 1 50 > 0.4 2 25 > 0.6 2 3 > 1.1 1 1500 > 1.4 1 18 > 1.6 2 2500 > 1.9 2 18 > 2.1 1 37 > ...

,我想将其转换为

> TimeOffset, Source, Length > 0.2 1 2550 > 0.6 2 28 > 1.4 1 1518 > 1.9 2 2518 > ...

尝试将其设置为英文,我想将连续记录与同一个源在一起,然后打印出每组中的单个记录,显示该组中的最高时间偏移量,来源和该组中长度的总和。

Trying to put this into English, I want to group consecutive records with the same 'Source' together, then printing out a single record per group showing the highest time offset in that group, the source, and the sum of the lengths in that group.

TimeOffset值得一直增加。

The TimeOffset values will always increase.

我怀疑这是可能的,但我真的不知道从哪里开始。在某种意义上,我可以输出数据帧,并在例如Python,但如果可能,我宁愿留在R中。

I suspect this is possible in R, but I really don't know where to start. In a pinch I could export the data frame out and do it in e.g. Python, but I'd prefer to stay within R if possible.

提前感谢您可以提供的任何帮助

Thanks in advance for any assistance you can provide

推荐答案

首先,您需要创建一个 id 变量,它指定您的组,而不依赖于它们是连续的事实。之后,它很简单。

First you need to create an id variable that specifies your groups without relying on the fact that they are consecutive. After that it is pretty straight forward.

> dat <- data.frame( TimeOffset = c(0,.1,.2,.4,.6,1.1,1.4,1.6,1.9,2.1), + Source=c(1,1,1,2,2,1,1,2,2,1), + Length=c(1500,1000,50,25,3,1500,18,2500,18,37)) > dat TimeOffset Source Length 1 0.0 1 1500 2 0.1 1 1000 3 0.2 1 50 4 0.4 2 25 5 0.6 2 3 6 1.1 1 1500 7 1.4 1 18 8 1.6 2 2500 9 1.9 2 18 10 2.1 1 37 > > id <- cumsum(c(TRUE,diff(dat$Source)!=0)) > id [1] 1 1 1 2 2 3 3 4 4 5 > > cbind(TimeOffset=tapply(dat$TimeOffset,id,max), + Source=tapply(dat$Source,id,max), + Length=tapply(dat$Length,id,sum)) TimeOffset Source Length 1 0.2 1 2550 2 0.6 2 28 3 1.4 1 1518 4 1.9 2 2518 5 2.1 1 37

更多推荐

在R中的数据帧中汇总分组记录

本文发布于:2023-11-22 08:27:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616686.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!