[R] grouping and counting in dataframe

jim holtman jholtman at gmail.com
Mon Feb 28 01:19:10 CET 2011


Here is one solution; mine differs since there should be at least one
item in the range which would be itself:

      tm gr
1  12345  1
2  42352  3
3  12435  1
4  67546  2
5  24234  2
6  76543  4
7  31243  2
8  13334  3
9  64562  3
10 64123  3
> d$ct <- ave(d$tm, d$gr, FUN = function(x){
+     # determine count in the range
+     sapply(x, function(a) sum((x >= a - 500) & (x <= a + 500)))
+ })
>
> d
      tm gr ct
1  12345  1  2
2  42352  3  1
3  12435  1  2
4  67546  2  1
5  24234  2  1
6  76543  4  1
7  31243  2  1
8  13334  3  1
9  64562  3  2
10 64123  3  2


On Sat, Feb 26, 2011 at 5:10 PM, zem <zmanolova at gmail.com> wrote:
> sry,
> new try:
>
> tm<-c(12345,42352,12435,67546,24234,76543,31243,13334,64562,64123)
> gr<-c(1,3,1,2,2,4,2,3,3,3)
> d<-data.frame(cbind(time,gr))
>
> where tm are unix times and gr the factor grouping by
> i have a skalar for example k=500
> now i need to calculate in for every row how much examples in the group are
> in the interval [i-500;i+500] and i is the active tm-element, like this:
>
>>d
>    time gr ct
> 1  12345  1  2
> 2  42352  3  0
> 3  12435  1  2
> 4  67546  2  0
> 5  24234  2  0
> 6  76543  4  0
> 7  31243  2  0
> 8  13334  3  0
> 9  64562  3  2
> 10 64123  3  2
>
> i hope that was a better illustration of my problem
>
> --
> View this message in context: http://r.789695.n4.nabble.com/grouping-and-counting-in-dataframe-tp3325476p3326338.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list