0

My question is maybe basic but I have not found the answer on stackoverflow and in the other sources. Thus, I put it here Example data set

yta<-rep(c(200, 201), each=10)
ala<-data.frame(yta)
ala$nr<-0

and now I want to loop over this data set and put the sequence form 1 to i in a new variable nr to unique(ala$yta). it is just example in my data set I have more yta which have uneven number of rows.

Legionista
  • 45
  • 1
  • 8

3 Answers3

0

Not very clear the expected output but maybe this what you want :

transform(ala,nr=ave(yta,yta,FUN=seq))
  yta nr
1  200  1
2  200  2
3  200  3
4  200  4
5  200  5
6  200  6
7  200  7
8  200  8
9  200  9
10 200 10
11 201  1
12 201  2
13 201  3
14 201  4
15 201  5
16 201  6
17 201  7
18 201  8
19 201  9
20 201 10
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • My I have a little explanation of the code. It works for the data set I gave but not for the big data set I have. – Legionista Oct 07 '14 at 07:13
0

Another way to do it with dplyr :

library(dplyr)
ala %>%
  group_by(yta) %>%
  mutate(nr=1:n())
juba
  • 47,631
  • 14
  • 113
  • 118
0

Using data.table (would be faster for big datasets)

library(data.table)
DT <- setDT(ala)[,nr:=seq_len(.N),by=yta]
DT
 #    yta nr
 #1: 200  1
 #2: 200  2
 #3: 200  3
 #4: 200  4
 #5: 200  5
 #6: 200  6
 #7: 200  7
 #8: 200  8
 #9: 200  9
#10: 200 10
#11: 201  1
#12: 201  2
#13: 201  3
#14: 201  4
#15: 201  5
#16: 201  6
#17: 201  7
#18: 201  8
#19: 201  9
#20: 201 10

data

yta<-rep(c(200, 201), each=10)
ala<-data.frame(yta)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662