1

How to make an index variable based on the number levels of a factor variable? Explicitly:

x=c(rep(letters[1:5], 3))
x=sort(x)
index=c(rep(1:3, 5))
data.frame(cbind(x,index))

   x index
1  a 1
2  a 2
3  a 3
4  b 1
5  b 2
6  b 3
7  c 1
8  c 2
9  c 3
10 d 1
11 d 2
12 d 3
13 e 1
14 e 2
15 e 3

I want to create index variable, in the above, for a large data.

overwhelmed
  • 225
  • 3
  • 12
  • You can find details for your question at - http://stackoverflow.com/questions/6112803/how-to-create-an-index-from-a-variable-in-a-dataframe – Shubham Tripathi May 20 '15 at 06:35
  • @Shubham Tripathi That example does not help. In that example index repeated with same value for same factor, but I want to increase index within a factor level. – overwhelmed May 20 '15 at 06:40

1 Answers1

2

This worked for me

library(dplyr)
x=c(rep(letters[1:5], 3))
x=sort(x)
index=c(rep(1:3, 5))
df <- data.frame(cbind(x,index))
df <- df %>% group_by(x) %>% mutate(index2= 1:n())
Keniajin
  • 1,649
  • 2
  • 20
  • 43