[R] Assign the number to each group of multiple rows

arun smartpink111 at yahoo.com
Wed Mar 13 20:48:22 CET 2013


Hi,
Try this:
data1<-data.frame(row=seq(1:10),beh=c(1,1,1,2,2,2,1,1,2,2))
data1<-within(data1, {trip.id<- cumsum(c(1,abs(diff(beh)))); Seq<-ave(row,trip.id,FUN=seq)})
 data1
#   row beh Seq trip.id
#1    1   1   1       1
#2    2   1   2       1
#3    3   1   3       1
#4    4   2   1       2
#5    5   2   2       2
#6    6   2   3       2
#7    7   1   1       3
#8    8   1   2       3
#9    9   2   1       4
#10  10   2   2       4
A.K.




----- Original Message -----
From: Lilia Dmitrieva <sealilia at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Wednesday, March 13, 2013 3:05 PM
Subject: [R] Assign the number to each group of multiple rows

Dear R users,



My data have repeating "beh" parameter : 1 or 2 - type of animal behavior
in subsequent locations. I need to assign unique number to each sequence of
locations.

My data is:


>data=data.frame(row=seq(1:10),beh=c(1,1,1,2,2,2,1,1,2,2))
>attach(data)
>data


   row beh

1    1    1

2    2    1

3    3    1

4    4    2

5    5    2

6    6    2

7    7    1

8    8    1

9    9    2

10  10    2


I need the output like this:

   row beh seq  trip.id

1    1    1   1       1

2    2    1   2       1

3    3    1   3       1

4    4    2   1       2

5    5    2   2       2

6    6    2   3       2

7    7    1   1       3

8    8    1   2       3

9    9    2   1       4
10  10   2   2      4

I managed to assign sequence numbers inside of each group:


> seq<-sequence(rle(beh)$length)

> new<-cbind(data,seq)
> new


   row beh seq

1    1    1   1

2    2    1   2

3    3    1   3

4    4    2   1

5    5    2   2

6    6    2   3

7    7    1   1

8    8    1   2

9    9    2   1

10  10   2   2



but I can’t assign the numbers to the groups (the parameter "trip.id")...  I
would appreciate any help.



Regards,



Lilia

    [[alternative HTML version deleted]]


______________________________________________
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.




More information about the R-help mailing list