Create new levels by grouping existing levels

Viewed 51

Let's say I have sample data like this that is continuous d <- rnorm(100)

Now I want to have this variable stored in a set of levels that correspond to specific intervals. For example, anything >-1 would be level 1, -1 < x < 0 would be level 2 and so on.

I know we can create a new variable to store the levels, but is there any way of doing it without creating an additional variable of just the levels, thereby preserving the data i.e, factoring the variable based on a condition?

I want something looks like this

d  
# [1] -0.129731527  0.832232654 -1.204235933  ...
str(d)  
# Factor w/ n levels "1", "2" ...
1 Answers

You can use cut for this:

#the second argument is where you specify the breaks that you want
dc <- cut(d, c(-Inf, -1, 0, 1, Inf))

The output will be a factor with the above ranges. Then if you want you can change the levels of that to numbers:

levels(dc) <- 1:4

But I would suggest to leave them like that, since they are numbers underneath anyway.

Related