[R] Help with for/if loop

andrew andrewjohnroyal at gmail.com
Fri Apr 24 04:20:36 CEST 2009


or perhaps

agec <- 0*age
age[age<=46] <- 1
age[age>46 & age<=58 <- 2
age[age>58] <- 3

or perhaps a one liner

cut(x = age, breaks= c(0,46, 58,Inf), labels = c(1,2,3))



On Apr 24, 11:24 am, Jorge Ivan Velez <jorgeivanve... at gmail.com>
wrote:
> Dear Hollie,
> ifelse() is one alternative in this particular case:
>
> # Some data
> age<- c(46,47,43,46,47,59,50,54,59,60)
>
> ifelse(age<=46, 1,
>         ifelse( age>46 & age<=58 , 2, 3) )
> [1] 1 2 1 1 2 3 2 2 3 3
>
> See ?ifelse for more details.
>
> HTH,
>
> Jorge
>
> On Thu, Apr 23, 2009 at 8:07 PM, Giggles_Fairy
> <giggles_fair... at hotmail.com>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])
> > }
>
> > 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!
>
> > Your replies will be very much appreciated!
>
> > Hollie
> > --
> > View this message in context:
> >http://www.nabble.com/Help-with-for-if-loop-tp23207428p23207428.html
> > Sent from the R help mailing list archive at Nabble.com.
>
> > ______________________________________________
> > R-h... at r-project.org mailing list
> >https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> >http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-h... at r-project.org mailing listhttps://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list