Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate sequence within group in R [duplicate]

Tags:

r

sequence

I am trying to obtain a sequence within category.

My data are:

A B 
1 1 
1 2
1 2
1 3
1 3
1 3
1 4
1 4

and I want to get variable "c" such as my data look like:

A B C
1 1 1
1 2 1
1 2 2
1 3 1
1 3 2
1 3 3
1 4 1
1 4 2
like image 732
ShrestR Avatar asked Sep 15 '13 17:09

ShrestR


People also ask

How do you replicate a sequence in R?

How do you Repeat a Sequence of Numbers in R? To repeat a sequence of numbers in R you can use the rep() function. For example, if you type rep(1:5, times=5) you will get a vector with the sequence 1 to 5 repeated 5 times.

How do you add sequential numbers in R?

The simplest way to create a sequence of numbers in R is by using the : operator. Type 1:20 to see how it works. That gave us every integer between (and including) 1 and 20 (an integer is a positive or negative counting number, including 0).


1 Answers

Use ave with seq_along:

> mydf$C <- with(mydf, ave(A, A, B, FUN = seq_along))
> mydf
  A B C
1 1 1 1
2 1 2 1
3 1 2 2
4 1 3 1
5 1 3 2
6 1 3 3
7 1 4 1
8 1 4 2

If your data are already ordered (as they are in this case), you can also use sequence with rle (mydf$C <- sequence(rle(do.call(paste, mydf))$lengths)), but you don't have that limitation with ave.

If you're a data.table fan, you can make use of .N as follows:

library(data.table)
DT <- data.table(mydf)
DT[, C := sequence(.N), by = c("A", "B")]
DT
#    A B C
# 1: 1 1 1
# 2: 1 2 1
# 3: 1 2 2
# 4: 1 3 1
# 5: 1 3 2
# 6: 1 3 3
# 7: 1 4 1
# 8: 1 4 2
like image 178
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 21 '22 11:10

A5C1D2H2I1M1N2O1R2T1