1

データ フレームには 2 つの列があります。左側の列は id を表し、右側の列には増加する整数が含まれています。連続したものとそうでないものがあります。整数の繰り返しはありません。私の目的は、連続する整数の平均数を取得することですid 。たとえば:

ここに私のデータセットの断片があります

station summary id

> データ
      イドモーメント
4448 1 11725
4540 1 11726
5457 1 11739
5519 1 11740
11733 1 11861
11797 1 11862
12020 1 11865
12313 1 11869
14576 1 11914
23314 1 12088
166 2 11644
278 2 11646
339 2 11647
407 2 11648
476 2 11649
545 2 11650
673 2 11652
737 2 11653
982 2 11657
1035 2 11658

上記のサンプルでは、 ​​id 1には次の数の連続する整数がありますmoment- 2, 2, 2, 1, 1, 1, 1 - したがって、平均は 1.428 になります。

id 2には、1、5、2、2 の連続する整数の数があるmomentため、平均は 2.5 になります。

実際のデータセットには、最大 200 行と 300 個の一意の ID があります。各 ID の平均が必要です。

何らかの方法で rle() 関数を使用する必要があることはわかっています。次のコードで最大数を見つけることができます。

集計( data$moment, dat['id'], FUN= function(d) max( rle( diff(d) )$lengths ) ) 

どのように平均を取りますか?

> dput(データ)
構造体(リスト(id = c(1L、1L、1L、1L、1L、1L、1L、1L、1L、1L、
2L、2L、2L、2L、2L、2L、2L、2L、2L、2L)、モーメント=c(11725L、11726L、
11739L、11740L、11861L、11862L、11865L、11869L、11914L、12088L、
11644L、11646L、11647L、11648L、11649L、11650L、11652L、11653L、
11657L, 11658L)), .Names = c("id", "moment"), row.names = c(4448L,
4540L、5457L、5519L、11733L、11797L、12020L、12313L、14576L、
23314L、166L、278L、339L、407L、476L、545L、673L、737L、982L、
1035L)、クラス = "data.frame")
4

1 に答える 1

3

There is probably a nicer way, but...

aggregate(data$moment,list(data$id), function(x) mean(rle(diffinv(diff(x)!=1))$lengths))
#   Group.1        x
# 1       1 1.428571
# 2       2 2.500000

Explanation

We first take the difference. We then look for those number that are not consecutive (diff(x)!=1). We then take the inverse of the difference (diffinv) to go back to the original length. We now have a vector that increments when at non-consecutive numbers. Take rle of that, then the lenghts and finally apply mean, and you're done.

Edit1: Removed a step that was unnecessary.

于 2016-02-20T17:52:02.943 に答える