ThallyHo
ThallyHo

Reputation: 2833

speeding up running if.. else loop in R

Does anyone know how to speed up running the following command? I want to replace the numerical "month" values with a character string ... e.g. month 1 goes to "Jul".

This command is really really slow as the dataframe I trying to implement it on is enormous!

for (i in 1:length(CO2$month)){
    if(CO2$month[i]=='1') {CO2$months[i]<-'Jul'} else
    if(CO2$month[i]=='2') {CO2$months[i]<-'Aug'} else
    if(CO2$month[i]=='3') {CO2$months[i]<-'Sept'} else
    if(CO2$month[i]=='4') {CO2$months[i]<-'Oct'} else
    if(CO2$month[i]=='5') {CO2$months[i]<-'Nov'} else
    if(CO2$month[i]=='6') {CO2$months[i]<-'Dec'} else
    if(CO2$month[i]=='7') {CO2$months[i]<-'Jan'} else
    if(CO2$month[i]=='8') {CO2$months[i]<-'Feb'} else
    if(CO2$month[i]=='9') {CO2$months[i]<-'Mar'} else
    if(CO2$month[i]=='10') {CO2$months[i]<-'Apr'} else
    if(CO2$month[i]=='11') {CO2$months[i]<-'May'} else
    if(CO2$month[i]=='12') {CO2$months[i]<-'Jun'}
}

Upvotes: 5

Views: 225

Answers (4)

Se&#241;or O
Se&#241;or O

Reputation: 17412

This would also work, even if it's for something where there's not a neat function like month.abb to use:

Mon <- data.frame(month=1:12, months=c("Jul","Aug","Sept","Oct","Nov","Dec",
                                "Jan","Feb","Mar","Apr","May","Jun"))
CO2 <- merge(CO2, Mon, by="month", all.x=TRUE)

Upvotes: 1

Joshua Ulrich
Joshua Ulrich

Reputation: 176638

You can do it without a loop and without if-else:

set.seed(21)
CO2 <- data.frame(month=as.character(sample(1:12,24,TRUE)),
  stringsAsFactors=FALSE)
MonthAbbRotated <- month.abb[c(7:12,1:6)]
CO2$months <- MonthAbbRotated[as.numeric(CO2$month)]

If your month column isn't really character, this is even easier:

set.seed(21)
CO2 <- data.frame(month=sample(1:12,24,TRUE))
MonthAbbRotated <- month.abb[c(7:12,1:6)]
CO2$months <- MonthAbbRotated[CO2$month]

Upvotes: 7

frankc
frankc

Reputation: 11473

I could be missing something, but why not just use a factor?

CO2$month <- factor(CO2$month, levels=1:12, labels=c("Jul","Aug","Sept","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun"))

Upvotes: 4

AGS
AGS

Reputation: 14498

month =c("jul","aug","sep","oct","nov","dec","jan","feb","mar","apr","may","jun")

for (i in 1:length(CO2$month)){ CO2$month[i] = month[as.integer(CO2$month[i])]}

Upvotes: 1

Related Questions