Skip to content
Prev 178154 / 398502 Next

Help with for/if loop

On Apr 23, 2009, at 8:07 PM, Giggles_Fairy wrote:

            
My help with your loop will be to eliminate it. Try:
# age= sample(20:120, 100, replace=T)
# use your own data

  agecatagory<- cut(age, breaks=c(0, 46, 58, max(age) ) )

  table(agecatagory)
#agecatagory
#  (0,46]  (46,58] (58,120]   #agecatagory is now a factor
#      31        9       60

  age.n <- as.numeric(agecatagory)
  table(age.n)
#age.n
# 1  2  3
#31  9 60

so a one liner would be:
agecatagory <- as.numeric( cut(age, breaks=c(0, 46, 58, max(age) ) ) )
David Winsemius, MD
Heritage Laboratories
West Hartford, CT