我们如何在引号

时间:2018-04-15 22:33:24

标签: r loops global-variables

我自己编写了所有这些(请查看下面的代码###)但我认为必须有一些方法可以在循环中执行此操作。如何编辑代码以编写类似于:

的循环
i=10

for (i in 10 to 80){

    j=i+5

    age_only$agecat[age_only$CI_Age.at.Adverse.Event>=i &        
               age_only$CI_Age.at.Adverse.Event<j] <- "Between i and j-1"

    i=j
 }

我不知道如何在引号内使用i/j

age_only$agecat[age_only$CI_Age.at.Adverse.Event] <- "Above 85"    
age_only$agecat[age_only$CI_Age.at.Adverse.Event<5]<-"Below 5"     
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=5 & age_only$CI_Age.at.Adverse.Event<10]<-"Between 5 to 9"     
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=10 & age_only$CI_Age.at.Adverse.Event<15]<- "Between 10 to 14"    
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=15 & age_only$CI_Age.at.Adverse.Event<20]<- "Between 15 to 19"    
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=20 & age_only$CI_Age.at.Adverse.Event<25]<- "Between 20 to 24"    
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=25 & age_only$CI_Age.at.Adverse.Event<30]<- "Between 25 to 29"    
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=30 & age_only$CI_Age.at.Adverse.Event<35]<- "Between 30 to 34"    
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=35 & age_only$CI_Age.at.Adverse.Event<40]<- "Between 35 to 39"    
  age_only$agecat[age_only$CI_Age.at.Adverse.Event>=40 & age_only$CI_Age.at.Adverse.Event<45]<-"Between 40 to 44"      
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=45 & age_only$CI_Age.at.Adverse.Event<50]<- "Between 45 to 49"    
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=50 & age_only$CI_Age.at.Adverse.Event<55]<-"Between 50 to 54"
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=55 & age_only$CI_Age.at.Adverse.Event<60]<- "Between 55 to 59"
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=60 & age_only$CI_Age.at.Adverse.Event<65]<- "Between 60 to 64"
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=65 & age_only$CI_Age.at.Adverse.Event<70]<- "Between 65 to 69"
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=70 & age_only$CI_Age.at.Adverse.Event<75]<- "Between 70 to 74"
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=75 & age_only$CI_Age.at.Adverse.Event<80]<- "Between 75 to 79"
age_only$agecat[age_only$CI_Age.at.Adverse.Event>=80 & age_only$CI_Age.at.Adverse.Event<85]<- "Between 80 to 84"`

1 个答案:

答案 0 :(得分:3)

尝试cut

age_only <- within(age_only, {
    agecat = cut(CI_Age.at.Adverse.Event, breaks = c(seq(0, 85, 5), 120))

   levels(agecat) <- sub("(\\(|\\[)(\\d*), ?(\\d*)(\\]|\\))", "Between \\2 and \\3",levels(agecat)) 
})

within让我可以修改数据框,而不必多次说age_only$sub命令会将级别从(5,10]转换为&#34;在5到10&#34;之间。