I did this the hard way and would like to know how you would do it with a loop/faster method. I'm creating labels for levels to use in a cut statement, working with age groups.
levels(age_group) <- ("<10","10-19","20-29","30-39","40-49","50-59","60-69","70-79","80-89","90-99","100-109",
"110-119","120-129","130+")
Does anyone have any good ideas about how to do this? The less "<10" and "130+" can be added manually but I'm sure there is a faster way to do the rest.
Thanks
It would probably be best to use the levels generated by cut, because your current intervals don't define which end is included.
s <- c(-Inf,seq(10,130,10),Inf)
levels(cut(s,s))
# [1] "(-Inf,10]" "(10,20]" "(20,30]" "(30,40]" "(40,50]"
# [6] "(50,60]" "(60,70]" "(70,80]" "(80,90]" "(90,100]"
# [11] "(100,110]" "(110,120]" "(120,130]" "(130, Inf]"
If you must use your current intervals, you can use this simple function:
strInterval <- function(start, end, by) {
s <- seq(start, end, by)
i <- paste(head(s,-1), s[-1]-1, sep="-")
c(paste0("<",start), i, paste0(end,"+"))
}
strInterval(10,130,10)
# [1] "<10" "10-19" "20-29" "30-39" "40-49" "50-59" "60-69"
# [8] "70-79" "80-89" "90-99" "100-109" "110-119" "120-129" "130+"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With