Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

r - create labels for interval

I am trying to create a label with cut and here is the example

> cut(c(1,5,10,15,160),c(0,5,10,15,Inf))
[1] (0,5]    (0,5]    (5,10]   (10,15]  (15,Inf]
Levels: (0,5] (5,10] (10,15] (15,Inf]

I wanted to automatically create labels like this

"1~5" "6~10" "11~15" "15+"

Is there any way I can do it automatically?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to do this automatically without manually specifying the labels you can do the manipulation as :

vec <- c(1,5,10,15,160)
breaks <- c(0,5,10,15,Inf)
n <- length(breaks)
labels <- paste(breaks[-n] + 1, breaks[-1], sep = '~')
labels[length(labels)] <- paste0(breaks[n - 1], '+')
cut(vec,breaks, labels)

#[1] 1~5   1~5   6~10  11~15 15+  
#Levels: 1~5 6~10 11~15 15+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...