user3079834 user3079834 - 1 month ago 7
R Question

R create range factor levels

I would like to automate the following procedure:

Get the min and max from a vector and define a step size from the min to the max given a specific step-size. Each value inside the vector now get's assigned to a

label
(factor level), that falls into this range e.g.
"20-30"
when the value is
27.45
.

At the moment I am using this for-loop

for (label_willi_counter in 1:length(willi)) {
if(willi[label_willi_counter] < 10)
label_willi = c(label_willi, "0 - 10")
else if(willi[label_willi_counter] < 20)
label_willi = c(label_willi, "10 - 20")
else if(willi[label_willi_counter] < 30)
label_willi = c(label_willi, "50 - 30")
else if(willi[label_willi_counter] < 40)
label_willi = c(label_willi, "30 - 40")
else if(willi[label_willi_counter] < 50)
label_willi = c(label_willi, "40 - 50")
else if(willi[label_willi_counter] < 60)
label_willi = c(label_willi, "50 - 60")
else if(willi[label_willi_counter] < 70)
label_willi = c(label_willi, "60 - 70")
else if(willi[label_willi_counter] < 80)
label_willi = c(label_willi, "70 - 80")
else if(willi[label_willi_counter] < 90)
label_willi = c(label_willi, "80 - 90")
else
label_willi = c(label_willi, "90 - 100")
}


Well it is working, but I'm sure there is a nicer (and probably faster) approach to do this. This example is fixed for the
minimum = 0
and
maximum = 100
and
step-size = 10
. I'm searching for a more general way to do this.

Answer

Try cut:

x
# [1] 60 35 21 30  6 19 49 17 59 93  9 96 46 63  3 58 13 86 47 16

cut(x, breaks = seq(0,100,10), labels = lbl)

#[1] 50-60  30-40  20-30  20-30  0-10   10-20  40-50  10-20  50-60  90-100 0-10   #90-100 40-50  60-70 
#[15] 0-10   50-60  10-20  80-90  40-50  10-20 
#Levels: 0-10 10-20 20-30 30-40 40-50 50-60 60-70 70-80 80-90 90-100

data

x <- c(60L, 35L, 21L, 30L, 6L, 19L, 49L, 17L, 59L, 93L, 9L, 96L, 46L, 
63L, 3L, 58L, 13L, 86L, 47L, 16L)

lbl <- c("0-10", "10-20", "20-30", "30-40", "40-50", "50-60", "60-70", 
"70-80", "80-90", "90-100")
Comments