Help with for/if loop
On Apr 23, 2009, at 8:07 PM, Giggles_Fairy wrote:
I have a set of data that includes various data columns. One if the
survival
time and another if a continuous variable of ages. I want to put the
ages
into intervals so that I can then perform the Kalpan Meier test. I
am trying
to use the following code to build a column with the age group
numbers in
agecatagory<-c( )
for (i in 1:137)
{
{
if(age[i]<=46) {agecat[i]<-1}
if(age[i]>46 & age[i]<= 58) {agecat[i]<-2}
if(age[i]>58) {agecat[i]<-3}
}
agecatagory<-c(agecatagory, agecat[i])
}
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) ) ) )
I have been getting various errors for various things and have
finally got
it so that only one error comes up
Error in if (age[i] <= 46) { : missing value where TRUE/FALSE needed
Could anyone pleaseeeeeee shed some light on this for me and tell em
where I
am going wrong. I am sure it is just a minor thing but I cant for
the life
of me figure it out!
David Winsemius, MD Heritage Laboratories West Hartford, CT