How to assign different index numbers to determined observations?

126 views Asked by At

What I want to do is assign a value of 1 to the first 1/3 of observations ofmy data, then a value of 2 to the second 1/3 of observations of my data and finally a value of 3 to the third 1/3 of observations of my data.

Taking into a ccount that my data consists of 30 observations, I did the following code:

c1 <- c(rep(1,10),rep(2,10),rep(3,10))

which I cbinded to my data

gala2 <- cbind(data,c1)

Then, for the first 10 observations (my first 1/3), the value of c1 is 1, for the next ten observations (second 1/3) the value of c1 is 2 and for the last ten observations (my third 1/3) the value of c1 is 3.

This works perfectly fine, but I wanted to ask if there is a way to do this in a more "abstract" way. That is, to tell R to assign the value of 1 to the first 1/3 of the data, assign the value of 2 to the second 1/3 and the value of 3 to the third 1/3?

Best regards,

2

There are 2 answers

0
Usobi On

Yes there is, try to take a look to cut(). To illustrate a bit try this with your example:

cut(yourDataAsNumeric,3,labels=FALSE)
0
Sven Hohenstein On

You can use

sort(rep_len(seq(3), length(c1)))

where c1 is your vector.