overwhelmed
overwhelmed

Reputation: 225

How to make an index variable in R

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.

Upvotes: 1

Views: 7670

Answers (1)

Keniajin
Keniajin

Reputation: 1659

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())

Upvotes: 2

Related Questions